使用@CompileStatic和泛型类时,构造函数无法应用于'(T)'错误

时间:2020-01-03 19:03:09

标签: generics groovy compile-static

我正在尝试“修补”我一直在升级的其他代码。

我将其简化为一个简单的示例通用类,然后使用该类。

首先,我像这样声明了一个通用的参数化类

//generic class 
class WillsAgent<T> {

    public  WillsAgent(T data) {//do nothing with this }
}

然后是一个使用此类的消费类

@CompileStatic
public abstract class Test<T> {



    public WillsAgent<T> agent( T state) {
        final WillsAgent<T> safe = new WillsAgent<T> (state)
        return safe
    }
}

正在播放@CompileStatic声明,IDE在(状态)下显示红色花键,将参数传递给这样的构造函数

screen shot

如果我注释掉@CompileStatic声明-错误消失

如果我将鼠标悬停在花体上(启用@CompileStatic),它将显示以下内容:Constructor 'WillsAgent' in 'groovyx.gpars.agent.WillsAgent<T>' cannot be applied to '(T)'

除了删除@CompileStatic

之外,我不知道该如何解决这个问题

有人有什么主意为什么要抱怨这一点以及如何解决它吗?

1 个答案:

答案 0 :(得分:1)

快速修复:替换以下行:

final WillsAgent<T> safe = new WillsAgent<T>(state)

具有:

final WillsAgent<T> safe = new WillsAgent(state)

第一行的问题可能是由IntelliJ IDEA的Groovy插件引起的。我尝试使用groovyc编译new WillsAgent<T>(state),但没有引发任何错误。另外,如果您在IDE中编译该类,则它也可以编译而不会出错。

好消息是,无论您编译new WillsAgent<T>(state)还是new WillsAgent(stage),在两种情况下都是从Groovy代码编译的字节码看起来与此类似:

//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by Fernflower decompiler)
//

package groovyx.gpars.agent;

import groovy.lang.GroovyObject;
import groovy.lang.MetaClass;

public class Test<T> implements GroovyObject {
    public Test() {
        MetaClass var1 = this.$getStaticMetaClass();
        this.metaClass = var1;
    }

    public WillsAgent<T> agent(T state) {
        WillsAgent safe = new WillsAgent(state);
        return safe;
    }
}
相关问题