0

我有一个非常复杂的类,它获取一个泛型值、一个功能接口和一些泛型类型的子类。现在我注意到一些与类型推断相关的奇怪行为。看看这段代码:

public class Test{
    public static class SubClass<F>{
        public SubClass(){}
    }

    @FunctionalInterface
    public interface FuncInterface {
        void operation(String s);
    }

    @SafeVarargs
    public <T> Test(T obj, FuncInterface fi, SubClass<T>...sc){}

    @SafeVarargs
    public <T> Test(T obj, SubClass<T>...sc){}

    public static void main(String[] args){
        Test t = new Test(
                    42,
                    (s)->{},
                    new SubClass<>());
    } 
}

行 Test t = new Test(...); 由于以下错误无法编译:

The constructor Test(int, (<no type> s) -> {}, new SubClass<>()) is undefined

现在我发现了两种不同的可能性来让这段代码工作:
1)为功能接口参数设置显式类型

Test t = new Test(
    42,
    (String s)->{},
    new SubClass<>());

2)或删除重载的构造函数。

/* public <T> Test(T obj, SubClass<T>...sc){} */

我真的不明白编译器的问题以及为什么我的解决方案有效。有人可以解释一下这里发生了什么。

4

1 回答 1

0

这肯定是 Eclipse 内部使用的 Eclipse Compiler for Java (ECJ) 的问题。要解决此问题,请将参数类型添加到 lambda:

public static void main(String[] args){
    Test t = new Test(
                42,
                (String s)->{},
                new SubClass<>());
} 

这样它编译得很好(至少在 Eclipse Luna 4.4.2 中)。

于 2015-11-26T15:10:02.090 回答