获取java中反射类的实例
我想得到一个反射类的实例。让我解释一下:获取java中反射类的实例,java,reflection,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 "M
我在“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
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
}
}
来自另一个计划(“B”计划):
我想做的一个更好的例子是:我不知道如何让“B”程序理解什么是net.package.Main
有什么想法吗?也许这是不可能的…让B.execute中的参数为Object类型 因此,您不会因为每个类都使用包名而感到困扰 扩展对象 包装: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());
}
}
包: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));
}
}
包装:stackoverflow
public class ReflectionTest {
@Test
public void callB() throws InstantiationException, IllegalAccessException, InvocationTargetException, NoSuchMethodException {
A myA = new A();
myA.callB();
}
}
我是用户傅
看起来你只是在要求多态性
Main
应该是一种类型,它有一个公共方法getUserInput()
,然后你可以调用它。是的,但我对getUserInput()的意思是,这个方法需要与“a”程序在同一个实例中,例如,一个从JTextField中提取文本的方法。我不能100%确定你在说什么,但是,如果要使用反射调用方法,则必须具有实例和方法,以及该方法的任何参数。因此,b.execute()
@markspace的最少两个参数当然,我知道,但我希望“b”程序在同一实例中从“A”程序请求数据。也许我没有很好地解释我自己。。。这个例子应该很容易理解:有帮助吗?问题是“A”和“B”类在不同的文件中。看一看我回复的pastebin@markspace.a和B在不同的包装中是的,它们是。这就是问题所在。我的意思是,在我的示例中,它们位于不同的包中。在“B”程序中使用导入是个好主意,但正如我前面所说的,“A”和“B”位于不同的jar文件中,因此我无法导入stackoverflow.Main。是否可以使用反射导入?