【问题标题】:Groovy Cannot Resolve Static ClassGroovy 无法解析静态类
【发布时间】:2016-11-29 18:55:56
【问题描述】:

我有以下 Groovy 脚本 test.groovy:

import test.Vehicle

def ok=new Vehicle();
def test=new Vehicle.Deserializer();

println "Hello, world!"

而且,我有 code/test/Vehicle.groovy,具有以下类定义:

package test;

public class Vehicle {
  public static class Deserializer {
  }
}

但是,以下命令失败:

groovy -cp code/ test.groovy

groovy -v 报告 2.4.7)

我希望它能够成功并打印“Hello, world”。相反,我得到:

org.codehaus.groovy.control.MultipleCompilationErrorsException: startup failed:
/tmp/test.groovy: 4: unable to resolve class Vehicle.Deserializer 
 @ line 4, column 10.
   def test=new Vehicle.Deserializer();
            ^

1 error

由于脚本在前一行没有失败,Groovy 可以毫无问题地找到 Vehicle 类。只是找不到Deserializer 静态类。

但是,这个脚本工作得很好:

public class Vehicle {
  public static class Deserializer {
  }
}

def ok=new Vehicle();
def test=new Vehicle.Deserializer();

println "Hello, world!"

当静态类(及其外部类)在单独的 Groovy 文件中定义时,我需要做些什么来让 Groovy 使用静态类?


更新:我找到了this issue,并且可以确认Groovy 至少可以看到Deserializer 类:

import test.Vehicle;
import static test.Vehicle.Deserializer;

println Deserializer.class.name

def ok=new Vehicle();
// def test=new Vehicle.Deserializer();

println "Hello, world!"

这按预期工作:

test.Vehicle$Deserializer
Hello, world!

但是,取消注释 def test=new Vehicle.Deserializer(); 仍然会给我错误,将其更改为 def test=new Deserializer(); 也是如此(给定 import static)。

【问题讨论】:

  • 我还没有测试过自己,但是您是否尝试过在test.groovy 中明确导入静态类作为import static test.Vehicle.Deserializer
  • @dmahapatro: import test.Vehicle.Deserializer 导致第二个“无法解析类”错误,指向该行。 import static test.Vehicle.Deserializer,奇怪的是,不会导致第二个错误,但它不会清除第一个错误。
  • 是的,见证了同样的事情。在执行test.groovy 之前,我还尝试通过groovyc 编译Vehicle.groovy,但我仍然看到它在抱怨。这可能是个问题。
  • test.groovyVehicle.groovy 放在同一个包中,编译Vehicle.groovy 然后运行groovy test.groovy 有效!!
  • @dmahapatro:我不确定“旁边”是什么意思。如果您的意思是“不在包中,例如我正在使用的 test”,则在我的情况下这不是一个选项,并且类似于我的工作脚本(问题中的最后一个代码 sn-p)。

标签: groovy


【解决方案1】:

看起来这是a known Groovy bug。如果你的静态类有一个零参数的构造函数,你可以通过newInstance() 解决这个问题:

import test.Vehicle;
import static test.Vehicle.Deserializer;

def ok=new Vehicle();
def test=Deserializer.class.newInstance();

println "Hello, world!"

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-12-01
    • 1970-01-01
    相关资源
    最近更新 更多