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

With the setter method, user can set any class that extends from "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:

public class MyCustomClass extends CustomClass<String> 

Upvotes: 4

Views: 1197

Answers (2)

Manuel Spigolon
Manuel Spigolon

Reputation: 12880

In the second statement you don't define type T so the compiler can't compile because of the restriction on setClass.

YOu should add T in the with function for variable purpose:

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

Upvotes: 1

Artur Biesiadowski
Artur Biesiadowski

Reputation: 3698

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.

Upvotes: 5

Related Questions