8

This is similar but not quite the same as Java: instantiating an enum using reflection

I have a Map<Enum<?>, FooHandler> that I want to use to map Enums (I don't care which type or even if they are the same type, just as long as they are enum constants) to my FooHandler class.

I would like to populate this map using a text file that I read. I can get it to work, but I have two warnings I would like to get around:

static private <E extends Enum<E>> E getEnum(String enumFullName) {
  // see https://stackoverflow.com/questions/4545937/
  String[] x = enumFullName.split("\\.(?=[^\\.]+$)");
  if (x.length == 2)
  {
    String enumClassName = x[0];
    String enumName = x[1];
    try {
      Class<E> cl = (Class<E>)Class.forName(enumClassName);
      // #1                          

      return Enum.valueOf(cl, enumName);
    }
    catch (ClassNotFoundException e) {
      e.printStackTrace();
    }
  }
  return null;
}

public void someMethod(String enumName, String fooHandlerName)
{
   FooHandler fooHandler = getFooHandler(fooHandlerName);
   Enum e = getEnum(enumName);
   // #2

   map.put(e, fooHandler);
}

Warning #1: unchecked cast Warning #2: Enum is a raw type.

I get #1 and could just put a warning I suppose, but I can't seem to beat warning #2; I've tried Enum<?> and that just gives me an error about generic type capture bound mismatch.


Alternative implementations that are worse: Before my <E extends Enum<E>> generic return value, I tried returning Enum and it didn't work; I got these warnings/errors:

static private Enum<?> getEnum(String enumFullName) {
   ...

Class<?> cl = (Class<?>)Class.forName(enumClassName);
    // 1
return Enum.valueOf(cl, enumName);
    // 2
}
  1. warnings:

      - Type safety: Unchecked cast from Class<capture#3-of ?> to Class<Enum>
      - Enum is a raw type. References to generic type Enum<E> should be parameterized
      - Enum is a raw type. References to generic type Enum<E> should be parameterized
      - Unnecessary cast from Class<capture#3-of ?> to Class<?>
    
  2. errors:

    - Type mismatch: cannot convert from capture#5-of ? to Enum<?>
    - Type safety: Unchecked invocation valueOf(Class<Enum>, String) of the generic method 
     valueOf(Class<T>, String) of type Enum
    - Bound mismatch: The generic method valueOf(Class<T>, String) of type Enum<E> is not 
     applicable for the arguments (Class<capture#5-of ?>, String). The inferred type capture#5-of ? is not 
     a valid substitute for the bounded parameter <T extends Enum<T>>
    

and this:

static private Enum<?> getEnum(String enumFullName) {
   ...
  Class<Enum<?>> cl = (Class<Enum<?>>)Class.forName(enumClassName);
  // 1
  return Enum.valueOf(cl, enumName);
  // 2
  1. warning: Type safety: Unchecked cast from Class<capture#3-of ?> to Class<Enum<?>>
  2. error: Bound mismatch: The generic method valueOf(Class<T>, String) of type Enum<E> is not applicable for the arguments (Class<Enum<?>>, String). The inferred type Enum<?> is not a valid substitute for the bounded parameter <T extends Enum<T>>
Community
  • 1
  • 1
Jason S
  • 184,598
  • 164
  • 608
  • 970

2 Answers2

6

For #1 there's no solution except SuppressWarnings("unchecked").

For #2 there's a problem with the declaration:

static private <E extends Enum<E>> E getEnum(String enumFullName)

You can return E, but there's no way for the compiler to determine E. There's no argument of type E or Class<E> or whatever, which would allow it. You can write it, but there'll be an unchecked cast somewhere and when you call it, you may get a ClassCastException. So don't do it.

Just change it into

static private Enum<?> getEnum(String enumFullName)

as this will work and is more fair. You'll get a warning on each call site and that's correct as there is something to warn of.

maaartinus
  • 44,714
  • 32
  • 161
  • 320
  • You can return `E` and there is a way for the compiler to determine it... it, like the type arguments of all generic methods, is determined at the call site. Often it's determined based on some argument(s) passed to the method (and it generally only makes sense to use generic methods this way) but it can also be determined based on how the return value is used. Like I said, though, it generally doesn't make sense to do that given that it's often a `ClassCastException` just waiting to happen. – ColinD Jan 20 '11 at 19:03
  • Agreed. I changed it to `static private Enum> getEnum(String enumFullName) { ... @SuppressWarnings("unchecked") final Class cl = (Class)Class.forName(enumClassName); @SuppressWarnings("unchecked") final Enum result = Enum.valueOf(cl, enumName); return result; }` but actually I'd better annotate the whole method with SuppressWarnings since it may throw a ClassCastException in case the class name denotes no Enum. – maaartinus Jan 20 '11 at 19:11
  • "Just change it into... Enum>" -- that doesn't work, I tried it beforehand and it is worse, it gives an error. – Jason S Jan 20 '11 at 19:13
  • It does, see my previous comment. – maaartinus Jan 20 '11 at 19:39
  • oh -- ok, thanks! Accepted because of your comment to fix it. – Jason S Jan 20 '11 at 20:18
6

The signature

static private <E extends Enum<E>> getEnum(String enumFullName)

isn't doing you any good here.

The <E extends Enum<E>> allows the caller of the method to assign the result of getEnum to any enum type they want without any casting:

SomeEnum e = getEnum("com.foo.SomeOtherEnum.SOMETHING"); // ClassCastException!

However, that doesn't make any sense... if the caller knew what specific type of enum the method would return, they could do something more sensible like SomeEnum.valueOf("SOMETHING").

The only thing that makes sense here is for getEnum to just return Enum<?>, which seems like what you really want to do anyway:

static private Enum<?> getEnum(String enumFullName) {
  String[] x = enumFullName.split("\\.(?=[^\\.]+$)");
  if(x.length == 2) {
    String enumClassName = x[0];
    String enumName = x[1];
    try {
      @SuppressWarnings("unchecked")
      Class<Enum> cl = (Class<Enum>) Class.forName(enumClassName);
      return Enum.valueOf(cl, enumName);
    }
    catch(ClassNotFoundException e) {
      e.printStackTrace();
    }
  }
  return null;
}

The above compiles with no warnings and works properly. The cast to Class<Enum> warning is suppressed because we know that it isn't safe to do that and that Enum.valueOf will blow up if the class with the given name isn't an enum class and that's what we want to do.

ColinD
  • 108,630
  • 30
  • 201
  • 202
  • "Just change it into... Enum>" -- that doesn't work, I tried it beforehand and it is worse, it gives an error. – Jason S Jan 20 '11 at 19:13
  • @Jason S: Nevermind, as @maaartinus commented, using `Class` as the type of the class you cast to rather than `Class>` or some variation seems to work. – ColinD Jan 20 '11 at 19:50