views:

3700

answers:

2

I was using an enum in which the constant was a Class. I needed to invoke a method on the constant but could not introduce a compile time dependency and the enum was not always available at runtime (part of optional install). Therefore, I wanted to use reflection.

This is easy, but I hadn't used reflection with enums before.

The enum looked something like this:

public enum PropertyEnum {

  SYSTEM_PROPERTY_ONE("property.one.name", "property.one.value"),

  SYSTEM_PROPERTY_TWO("property.two.name", "property.two.value");

  private String name;  

  private String defaultValue;

  PropertyEnum(String name) {
    this.name = name;
  }

  PropertyEnum(String name, String value) {
    this.name = name;
    this.defaultValue = value;
  } 

  public String getName() {
    return name;
  }

  public String getValue() {
    return System.getProperty(name);
  }

  public String getDefaultValue() {
    return defaultValue;
  }  

}

What is an example of invoking a method of the constant using reflection?

+6  A: 
import java.lang.reflect.Method;

class EnumReflection
{

  public static void main(String[] args)
    throws Exception
  {
    Class<?> clz = Class.forName("test.PropertyEnum");
    /* Use method added in Java 1.5. */
    Object[] consts = clz.getEnumConstants();
    /* Enum constants are in order of declaration. */
    Class<?> sub = consts[0].getClass();
    Method mth = sub.getDeclaredMethod("getDefaultValue");
    String val = (String) mth.invoke(consts[0]);
    /* Prove it worked. */
    System.out.println("getDefaultValue " + 
      val.equals(PropertyEnum.SYSTEM_PROPERTY_ONE.getDefaultValue()));
  }

}
David G
can you (or any edit person) format this answer a little nicer?
Jay R.
it was ugly. hope it's more readable now.
David G
Sorry, I may have clobbered your edit; I guess SO doesn't have very sophisticated version reconciliation. However, beyond formatting, my changes use Java 5 source conventions.
erickson
no problem about clobbering my edits. your version is easier to read and good idea using Java 5 conventions.
David G
better, thanks. :)
Jay R.
+4  A: 

Examining enums via reflection is covered quite nicely here

Steve K
I agree that's good coverage of the topic.
David G