dimanche 8 juillet 2018

Java Class Reflection: init external class with wild card parameters

I have searched for the solution of this question 2 days long and now must ask it here :-( My Problem:

I have created new custom Java Class:

package my.app.test;

class Test extends Object {
    Test(){

    }

    public void print(){
        System.out.println("success");
    }
}

I another package i have:

package my.app.test2;

public class Test2 {
    Test2(Class<? extends Object> Test){

    }

    public void execute(Class<? extends Object> Test){

    }
}

Now i want to inflate Test2.class with Test.class as on of parameters:

package my.app.test;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class Index {
    Index(){}

    static public void inflate(){
        ClassLoader loader = Thread.currentThread().getContextClassLoader();
        if(loader != null)
            try {
                Class<?> Test2 = Class.forName("my.app.test2.Test2", false, loader);
                if(Test2 != null){
                    Class<?>[] types = new Class[1];
                    types[0] = Test.class;
                    Method m = Test2.getDeclaredMethod("execute", types);
                    m.setAccessible(true);
                    try {
                        m.invoke(Test.class, new Test());
                    } catch (IllegalAccessException e) {
                        e.printStackTrace();
                    } catch (InvocationTargetException e) {
                        e.printStackTrace();
                    }
                }
            } catch (NoSuchMethodException | ClassNotFoundException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
    }
}

But i get error :

java.lang.NoSuchMethodException: my.app.test2.Test2.execute(my.app.test.Test)

If it's possible to do that?





Aucun commentaire:

Enregistrer un commentaire