在java中获取反射类的实例

时间:2016-03-19 02:20:04

标签: java reflection

我想获得一个反射类的实例。让我解释一下:
我在'A'程序中创建了一个反射方法的新实例:

// Before this, class loading and stuff that are not transcendental for this situation.
Method executeApp = loadedClass.getMethod("execute", Main.class)
executeApp.invoke(loadedClassInstance, MAIN); // This "MAIN" is an instance of "Main" class

从另一个程序('B'程序):

public class b {
  public void execute(net.package.Main instance) {
    System.out.println(instance.getUserInput()); // Just an example, the point is to get information from the instance
  }
}

我正在尝试做的一个更好的例子是:http://pastebin.com/61ZR9U0C
我不知道如何让'B'程序理解什么是net.package.Main
任何的想法?也许这是不可能的......

1 个答案:

答案 0 :(得分:2)

让B.execute中的参数为Object类型 因此,您不会因为每个类而烦恼包名 extends Object

package:stackoverflow

import stackoverflow.somepackage.B;
class Main{

        public String getUserInput(){
            return "I 'am user foo";
        }

}

class A{

    public void callB() throws NoSuchMethodException, IllegalAccessException, InstantiationException, InvocationTargetException {
        Class loadedClass = B.class;
        Method executeApp = loadedClass.getMethod("execute", Object.class);
        executeApp.invoke(loadedClass.newInstance(),Main.class.newInstance());
    }

}

package:stackoverflow.somepackage

class B{

    public void execute(Object object) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
        Class mainClass = object.getClass();

        // for your purpose
        // Method method = mainClass.getMethod("setLabelText", String.class);
        // String text = "Some Text";
        // method.invoke(object, text);

        // for demonstration
        Method method = mainClass.getMethod("getUserInput");
        System.out.println(method.invoke(object));
    }

}

package:stackoverflow

public class ReflectionTest {

    @Test
    public void callB() throws InstantiationException, IllegalAccessException, InvocationTargetException, NoSuchMethodException {
        A myA = new A();
        myA.callB();
    }


}
  

我是用户foo