Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling Enum.<T>valueOf() giving unchecked cast warning, despite T being declared <T extends Enum<T>>

This has to be something small, but I'm not getting it.

Why is this causing an unchecked cast compiler warning, when it has the exact same generic declaration as in Enum's valueOf?

public static final <T extends Enum<T>> Enum toValue(T for_value, String value)  {
   try  {
      return  Enum.<T>valueOf((Class<T>)for_value.getClass(), value);
   }  catch(RuntimeException rx)  {
      throw  new IllegalArgumentException(value);
   }
}

Compiler warning:

R:\jeffy\programming\sandbox\xbnjava\xbn\util\EnumUtil.java:92: 
warning: [unchecked] unchecked cast
         Enum.<T>valueOf((Class<T>)for_value.getClass(), value);
                                                     ^
  required: Class<T>
  found:    Class<CAP#1>
  where T is a type-variable:
    T extends Enum<T> declared in method <T>toValue(T,String,String)
  where CAP#1 is a fresh type-variable:
    CAP#1 extends Enum from capture of ? extends Enum
R:\jeffy\programming\sandbox\xbnjava\xbn\util\EnumUtil.java:98: error: missing return statement
   }
   ^
1 error
1 warning

It also happens in one or both of the generics are removed from the function call, such as

Enum.valueOf(for_value.getClass(), value);

This is the closest question I've found: Enum.valueOf throws a warning for unknown type of class that extends Enum?. This enum's type is known.

like image 709
aliteralmind Avatar asked Dec 19 '22 15:12

aliteralmind


1 Answers

You should be calling getDeclaringClass(), which will also fix the generics issues (it is specified to return Class<T>). Calling getClass() on an enum constant with its own methods defined can actually return a different class from the enum type.

like image 88
Louis Wasserman Avatar answered May 01 '23 12:05

Louis Wasserman