I have a generic class MyClass with a static factory method and a setter method:
public class MyClass {
public static MyClass with(Context context) {
MyClass myClass = new MyClass<>();
myClass.context = context;
return myClass;
}
public void setClass(Class extends CustomClass> customClass) {
...
}
...
}
With the setter method, user can set any class that extends from "CustomClass".
So far so good. If I do:
MyClass 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 cannot be converted to Class extends MyCustomClass>
I don't know why it wont compile with the second option. MyCustomClass is like:
public class MyCustomClass extends CustomClass
解决方案
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.with(this).setClass(MyCustomClass.class);
so it knows you will be 'talking strings' to it.