lundi 25 mai 2020

How to get Instance of a Class using reflection in java having generics parameter and return type method?

public enum E{
E1,E2,E3
}

public Class Service{
...
}

public interface A<RET>{
  RET get();
}

public interface AI<RET,CONF> extends A<RET>{
   void conf(CONF ...args);
}

public class AC implements AI<Service,E>{
  public void conf(E ...args){
   ....
 }
public Service get(){
  return new Service();
}
}

Now when I am trying with reflection to create Instance of Class "AC" I am getting error:

public Class MyReflectionAPI{
  public Object getInstance(){
       Class <? extends AI> aClass = (Class <? extends AI>) Class.forName("AC");
       Constructor<? extends AI> aCon = aClass.getConstructor(null);
       AI ai = aCon.newInstance((Object[]) null);

        Class<?> typeArg = Class.forName("[L"+"E"+";");
        Method valueOfTypeArg = typeArg.getMethod("valueOf", String.class);
        Object obj[] = new Object[]{valueOfTypeArg.invoke(typeArg,"E1")};
        ai.conf(obj);
    }

}

giving me the error: Exception in thread "main" java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to [E;

Is there any way of getting an object of Instance of AC with a generic objects passed to it?





Aucun commentaire:

Enregistrer un commentaire