21

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?

1
  • You've explained your enum class, but what is your question? Are you wondering what the code will look like to discover your class by reflection? Commented Sep 26, 2008 at 16:29

1 Answer 1

42
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()));
  }

}
Sign up to request clarification or add additional context in comments.

1 Comment

Why do you need the consts[0].getClass() call? Isn't this by definition the same as clz? In other words, isn't it possible to access getDefaultValue using clz.getDeclaredMethod() instead of sub.getDeclaredMethod?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.