首页 > 解决方案 > 如何使用反射在 Enum 类上调用方法

问题描述

需要调用枚举类上的方法,我没有直接的构建依赖。我想使用 java 的反射调用枚举类上的方法。

我也尝试过使用该字段,但没有运气

class myClass
{
  public void validateObjectType(Object obj)
  {
    Class<?> cls = Class.forName("package1.myEnum");
    Class [] parameterTypes = {Object.class};
    Method method = cls.getDeclaredMethod("getMyEnum", parameterTypes );
    String enumType = (String)method.invoke(null, new Object[]{obj1}); 

    Field enumTypeField = cls.getField(enumType );

   // -- invoke method getLocalName() on the object of the enum class.??
   Class [] parameters = {String.class};
            Method method1= cls.getDeclaredMethod("getLocalName", parameters);

String localizedName = (String) method1.invoke(enumTypeField , new Object[] {enumType});

  }

}

但是我在

method1.invoke(enumTypeField , new Object[] {}) // 

错误 :

java.lang.IllegalArgumentException: object is not an instance of declaring class

套餐一:

class enum myEnum
{

  A, 
  B;

 public static myEnum getMyEnum(Object a)
 {
   // business logic.
   // -- based on the type of object decide MyEnum
   if (null != object) return B;
   else  return A ;
 }

 public String getLocalName(String value)
 {
   if (value.equal(A.toString) return "my A";
   else if(value.equal(B.toString) return "my B";   
 }

}

套餐二:

// -- 这里我没有对包 1 的构建依赖。 // --- 不想添加,因为它会导致循环依赖

class myClass
{

  public void validateObjectType(Object obj)
  {
    Class<?> cls = Class.forName("package1.myEnum");
    Class [] parameterTypes = {Object.class};
    Method method = cls.getDeclaredMethod("getMyEnum", parameterTypes );
    ?? = (??)method.invoke(null, new Object[] {obj1}); // will get the Enum but dont have acces

   // -- invoke method getLocalName() on the object of the enum class.??
  }

}

标签: javareflection

解决方案


您的错误是试图将结果getMyEnum转换为String. getMyEnum返回 a myEnum,因此您不应将其转换为 a String。只需将其保留为Object

Class<?> cls = Class.forName("package1.myEnum");
Class [] parameterTypes = {Object.class};
Method method = cls.getDeclaredMethod("getMyEnum", parameterTypes);
Object enumValue = method.invoke(null, obj);

而且由于您说getLocalName实际上不接受任何参数,因此您可以获取该方法并像这样调用它:

Method method1= cls.getDeclaredMethod("getLocalName");

String localizedName = (String) method1.invoke(enumValue); // <-- using enumValue here!
System.out.println(localizedName);

您不需要该enumTypeField变量,因为enumValue它已经是我们要调用的枚举值getLocalName


推荐阅读