Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generics doesn't work for return type

Tags:

java

enums

How come java doesn't allow the following generic return type:

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

While the following does work:

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

getEnum(MyEnum.class); 

MyEnum is an enumaration that implements the interface MyInterface.

Why am I not allowed to return MyEnum.class?

EDIT:

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

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

But what would then then be the return type of the interface method to allow any Class object of a class that is both an enum and implements MyInterface?

like image 369
Thirler Avatar asked Apr 10 '26 01:04

Thirler


1 Answers

Your method is parameterized by T - the idea is that the caller gets to specify what T is - not the method implementation.

The call to the second method works because T is implicitly specified (by the caller) to be MyEnum.

like image 166
Jon Skeet Avatar answered Apr 12 '26 14:04

Jon Skeet