奇怪的类型推断行为

时间:2015-11-26 11:26:32

标签: java generics lambda constructor-overloading inferred-type

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

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<>());
    } 
}

测试线t =新测试(...);因以下错误而无法编译:

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){} */

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

1 个答案:

答案 0 :(得分:0)

它确实是Eclipse Compiler for Java(ECJ)的一个问题,Eclipse内部使用它。为了解决它,将参数类型添加到lambda:

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

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

相关问题