assylias
assylias

Reputation: 328598

Access enum name through reflection

I am trying to access the name of an enum through reflection (the name field of the Enum class) but I get a NoSuchFieldException.

See below a simple example: the program prints 5 for the Integer but throws an Exception for the enum.

Is there an elegant way to get the inspect method to work for enums?

public class Test {
  static enum A {
    A;
  }
  public static void main(String[] args) throws Exception {
    Integer i = 5;
    System.out.println(inspect(i, "value")); // prints 5, good

    A a = A.A;
    System.out.println(inspect(a, "name"));  // Exception :-(
  }

  private static Object inspect(Object o, String fieldName) throws Exception {
    Field f = o.getClass().getDeclaredField(fieldName);
    f.setAccessible(true);
    return f.get(o);
  }
}

Upvotes: 1

Views: 463

Answers (1)

Alex
Alex

Reputation: 7926

getField or getDeclaredField methods will only return positive results for fields declared in called class. They will not search for fields declared in superclasses. So, to get the refference for name field, you'll need to go deeper. Get the superclass reference (which in your case will be Enum class) and search for name field there.

o.getClass().getSuperclass().getDeclaredField(fieldName);

Upvotes: 2

Related Questions