Generics do not work for return type

Why Java does not allow the following return type:

public <T extends Enum<T> & MyInterface> Class<T> getEnum() {
    return MyEnum.class;
}

While the following works:

public <T extends Enum<T> & MyInterface> Class<T> getEnum(Class<T> t) {
    return t;
}

getEnum(MyEnum.class); 

MyEnumis an enumeration that implements an interface MyInterface.

Why am I not allowed to return MyEnum.class?

EDIT:

I need this because the function getEnum()is in the interface. It can be defined as follows:

@Override
public Class<MyEnum> getEnum() {
    return MyEnum.class;
}

But what then would be the type of the return method of the interface, allowing any object of the Classclass, which is both an enumeration and implements MyInterface?

+3
source share
2 answers

T - , , T - .

, T () MyEnum.

+7

:

:

public interface MyEnumReturner <T extends Enum<T> & MyInterface>
{
    public Class<T> getEnum(Class<T> t);
}

, , , :

public class MyClass implments MyEnumReturner<MyEnum>
{
    @Override
    public Class<MyEnum> getEnum() {
        return MyEnum.class;
    }

}
+2

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


All Articles