包装类<>类型泛型错误 [英] Wrapping a Class<?> type generics error
本文介绍了包装类<>类型泛型错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我没有跟踪为什么这段代码显示这个编译错误。
错误是:
类型不匹配:无法从TestClass.Wrapper转换< List< capture#1-of?>>到TestClass.Wrapper< List<>>
代码如下。
package test.cls;
import java.util.List;
public class TestClass
{
static abstract class Wrapper< A>
{
public abstract一个wrapped();
}
public static< A>包装< a取代; wrap(final A val)
{
return new Wrapper< A>()
{
public A wrap()
{
return val;
}
};
}
public static void main(final String [] args)
{
final List<?> list = null;
final Class<?> c = null;
final Wrapper< List<>> wrapList = wrap(list); // Error here
final Wrapper< Class <?>> wrapC = wrap(c); // Error here
}
}
解决方案
编译器的泛型类型推断在嵌套的通配符捕获上窒息。您需要明确指定类型参数:
final Wrapper< List<>> wrapList = TestClass。< List<>> wrap(list);
final Wrapper< Class <?>> wrapC = TestClass。< Class<>> wrap(c);
I'm not following why this code shows this compile error.
Error is:
Type mismatch: cannot convert from TestClass.Wrapper<List<capture#1-of ?>> to TestClass.Wrapper<List<?>>
Code is below.
package test.cls;
import java.util.List;
public class TestClass
{
static abstract class Wrapper<A>
{
public abstract A wrapped();
}
public static <A> Wrapper<A> wrap(final A val)
{
return new Wrapper<A>()
{
public A wrapped()
{
return val;
}
};
}
public static void main(final String[] args)
{
final List<?> list = null;
final Class<?> c = null;
final Wrapper<List<?>> wrapList = wrap(list); // Error here
final Wrapper<Class<?>> wrapC = wrap(c); // Error here
}
}
解决方案
The compiler's generic type inferrence is choking on the nested wildcard captures. You need to explicitly specify the type arguments:
final Wrapper<List<?>> wrapList = TestClass.<List<?>>wrap(list);
final Wrapper<Class<?>> wrapC = TestClass.<Class<?>>wrap(c);
这篇关于包装类<>类型泛型错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文