Domanda

Stavo usando un enum in cui la costante era una classe. Avevo bisogno di invocare un metodo sulla costante ma non potevo introdurre una dipendenza del tempo di compilazione e l'enum non era sempre disponibile in fase di esecuzione (parte dell'installazione opzionale). Pertanto, volevo usare la riflessione.

Questo è facile, ma non avevo mai usato la riflessione con gli enum.

L'enum era simile a questo:

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;
  }  

}

Qual è un esempio di invocazione di un metodo della costante usando la riflessione?

È stato utile?

Soluzione

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

}
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top