java java泛型编译错误
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4896259/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
java generics compilation error
提问by duduamar
I've the following generic class:
我有以下通用类:
public class GenericClass<E,T extends Comparable<T>>
{
public static <E, T extends Comparable<T>> GenericClass<E, T> create()
{
return new GenericClass<E, T>();
}
private GenericClass()
{
}
}
And this is how I simply use it:
这就是我简单地使用它的方式:
GenericClass<MyClass, Double> set = GenericClass.create();
Eclipse compilation shows no errors, however - building with ant provides the following error:
Eclipse 编译没有显示错误,但是 - 使用 ant 构建提供了以下错误:
MyClass.java:19: incompatible types; no instance(s) of type variable(s) E,T exist so that GenericClass<E,T> conforms to GenericClass<MyClass,java.lang.Double>
[javac] found : <E,T>GenericClass<E,T>
[javac] required: GenericClass<MyClass,java.lang.Double>
[javac] GenericClass<MyClass, Double> set = GenericClass.create();
Thanks!
谢谢!
采纳答案by Grzegorz Oledzki
Try using this:
尝试使用这个:
GenericClass<String, Double> set = GenericClass.<String,Double>create();
The Eclipse compiler and javac differ in their tolerance.
Eclipse 编译器和 javac 的容错性不同。
回答by cadrian
Your expression GenericClass.create()
bears no indication of type, so the compiler cannot infer the real type of E and T. You need to change the prototype of your function to help the compiler.
您的表达式GenericClass.create()
没有类型指示,因此编译器无法推断 E 和 T 的真实类型。您需要更改函数的原型以帮助编译器。
The simplest way is to pass the classes.
最简单的方法是传递类。
Example:
例子:
public class GenericClass<E,T extends Comparable<T>> {
public static <E, T extends Comparable<T>> GenericClass<E, T> create(Class<E> e, Class<T> t) {
return new GenericClass<E, T>();
}
private GenericClass() {
}
}
GenericClass<MyClass, Double> set = GenericClass.create(MyClass.class, Double.class);