[英]Java generics: incompatible types
I have a generic class MyClass<T>
with a static factory method and a setter method: 我有一个泛型类MyClass<T>
,带有静态工厂方法和setter方法:
public class MyClass<T> {
public static <T> MyClass<T> with(Context context) {
MyClass<T> myClass = new MyClass<>();
myClass.context = context;
return myClass;
}
public void setClass(Class<? extends CustomClass<T>> customClass) {
...
}
...
}
With the setter method, user can set any class that extends from "CustomClass". 使用setter方法,用户可以设置从“CustomClass”扩展的任何类。
So far so good. 到现在为止还挺好。 If I do: 如果我做:
MyClass<String> myClass = MyClass.with(this);
myClass.setClass(MyCustomClass.class);
It works perfectly. 它完美地运作。 But if I do: 但如果我这样做:
MyClass.with(this).setClass(MyCustomClass.class);
It does not compile! 它不编译! The compiler outputs: 编译器输出:
Error:(44, 87) error: incompatible types: Class<MyCustomClass> cannot be converted to Class<? extends MyCustomClass<Object>>
I don't know why it wont compile with the second option. 我不知道为什么它不会用第二个选项编译。 MyCustomClass
is like: MyCustomClass
就像:
public class MyCustomClass extends CustomClass<String>
Please note that you got information missing between your working example and your one-liner which has compilation error. 请注意,您的工作示例和具有编译错误的单行程序之间缺少信息。
It doesn't know the specialization. 它不知道专业化。 You need to do something like 你需要做点什么
MyClass.<String>with(this).setClass(MyCustomClass.class);
so it knows you will be 'talking strings' to it. 所以它知道你会“与它说话”。
In the second statement you don't define type T
so the compiler can't compile because of the restriction on setClass
. 在第二个语句中,您没有定义类型T
因此编译器无法编译,因为对setClass
的限制。
YOu should add T
in the with
function for variable purpose: 你应该在with
函数中添加T
以用于可变目的:
public static <T> MyClass<T> with(Object context, Class<T> clazz) {
MyClass<T> myClass = new MyClass<>();
myClass.context = context;
return myClass;
}
MyClass.with(this, String.class).setClass(MyCustomClass.class);
or pass: 或通过:
MyClass.<String>with(this).setClass(MyCustomClass.class);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.