Java generics: incompatible types

I have a generic class MyClass<T>with a static factory method and a setter method:

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) {
        ...
    }
    ...
}

Using the setter method, the user can set any class that extends from the "CustomClass".

So far so good. If I do this:

MyClass<String> myClass = MyClass.with(this);
myClass.setClass(MyCustomClass.class);

It works great. But if I do this:

MyClass.with(this).setClass(MyCustomClass.class);

It does not compile! Compiler output:

Error:(44, 87) error: incompatible types: Class<MyCustomClass> cannot be converted to Class<? extends MyCustomClass<Object>>

I do not know why it will not compile with the second option. MyCustomClassas follows:

public class MyCustomClass extends CustomClass<String> 
+4
source share
2 answers

Please note that you have information missing between your working example and your one-liner client with a compilation error.

. -

MyClass.<String>with(this).setClass(MyCustomClass.class);

, " ".

+5

T, - setClass.

T with :

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

:

MyClass.<String>with(this).setClass(MyCustomClass.class);
+1

Source: https://habr.com/ru/post/1648618/


All Articles