user2651804
user2651804

Reputation: 1614

How to avoid casting with generic return values?

For the method getFirstFromEnum below it is always true that the returned enum type is the class that was passed as an argument. Considering that, is there anyway I could alter the method to avoid casting every time I call it?

private <E extends Enum<?>> Enum<?> getFirstFromEnum(Class<E> enumClass) {
    return enumClass.getEnumConstants()[0];
}

EnumA foo = (EnumA) getFirstFromEnum(EnumA.class); //can I change method to avoid casting?

Upvotes: 1

Views: 95

Answers (1)

davidxxx
davidxxx

Reputation: 131526

Actually you return Enum<?>.
What you want to return is the Enum value of the passed enum as argument.
So, specify E as return value as it represents the specific Enum type you passed.

You could so write :

private <E extends Enum<?>> E getFirstFromEnum(Class<E> enumClass) {
  return enumClass.getEnumConstants()[0];
}

Upvotes: 5

Related Questions