簡體   English   中英

如何使用反射在Enum類上調用方法

[英]How to invoke method on Enum class using reflection

需要在枚舉類上調用該方法,我沒有直接的構建依賴性。 我想使用Java使用反射在enum類上調用該方法。

我也嘗試過使用Field,但沒有運氣

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

套餐1:

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.??
  }

}

您的錯誤是試圖將getMyEnum的結果轉換為String getMyEnum返回一個myEnum ,因此您不應將其轉換為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的枚舉值。

Method.invoke調用需要該方法來自的對象類型作為第一個參數。 您正在傳遞Field (在第二個調用中)。

如果要通過名稱獲取特定的枚舉,則可以使用valueOf方法並將其傳入。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM