开发者

Generics doesn't work for return type

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 ge开发者_运维问答tEnum() 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?


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.


I've found the answer to my second question too:

The interface with the generic type needs to be parameterized:

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

Then the class implementing the interface defines which type to use:

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

}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜