枚举类型为类时如何使用Java反射?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/140537/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 08:48:50  来源:igfitidea点击:

How to use Java reflection when the enum type is a Class?

javareflectionenums

提问by David G

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?

使用反射调用常量方法的示例是什么?

采纳答案by David G

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

}