vendredi 21 juin 2019

How to invoke method on Enum class using reflection

Need to call the method on the enum class, which i dont have direct build dependency. I want to call the method on enum class using the reflection using java.

I have tried using the Field as well, but no luck

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

  }

}

However i am getting error at method1.invoke(enumTypeField , new Object[] {}) //

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

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

}

Package 2:

// -- Here i dont have build dependency on package 1. // --- dont want to add, as it will lead to cyclic dependency 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.??
  }

}





Aucun commentaire:

Enregistrer un commentaire