Java 反射获取方法

Java 反射获取方法,java,reflection,Java,Reflection,我之前的帖子不是很清楚,很抱歉。我将尝试给出一个更好的例子,说明我正在努力做什么 我有一个Java应用程序,它将加载.class文件并在一个特殊的环境中运行它们(Java应用程序有内置函数)。注意:这不是一个库 Java应用程序将显示一个小程序,我想修改小程序中的变量 小程序的主类称为“客户端”。 Java应用程序将通过创建类“client”的新实例来加载小程序 我已经可以访问“客户端”类。Java应用程序将小程序放入一个变量中: Applet client = (Applet) loadedC

我之前的帖子不是很清楚,很抱歉。我将尝试给出一个更好的例子,说明我正在努力做什么

我有一个Java应用程序,它将加载.class文件并在一个特殊的环境中运行它们(Java应用程序有内置函数)。注意:这不是一个库

Java应用程序将显示一个小程序,我想修改小程序中的变量

小程序的主类称为“客户端”。 Java应用程序将通过创建类“client”的新实例来加载小程序

我已经可以访问“客户端”类。Java应用程序将小程序放入一个变量中:

Applet client = (Applet) loadedClientClass.newInstance();
所以我这样做了:

Class<?> class_client = client.getClass();
如果我尝试以下方法:

class_client.getDeclaredMethod("otherClass.someVoid",boolean.class);
它将失败,表示找不到该函数

“otherClass”是直接类名,据我所知,它不是对该类新实例的引用


有没有办法获取“otherClass.someVoid”?

如果该类未初始化,则var
someInteger
不存在。它是一个成员变量,因此它只存在于类的实例内部。所以,你不能改变它,因为它不存在。现在,如果你把它变成一个静态变量,那么你可以改变它

有没有办法通过 “mainClass”类

没有

但您可以通过以下方式通过
OtherClass
”类获得:

Class theOtherClazz=Class.forName(“OtherClass”);

然后通过otherclazz.getDeclaredMethod获取方法

您正在使用的
getDeclaredMethod
就像静态方法一样(期望它从任何类返回方法),但它只从类本身返回方法。下面是如何调用
otherClass.someVoid(false)

Class otherClass=Class.forName(“com.xyz.otherClass”);//上课
Method=otherClass.getDeclaredMethod(“someVoid”,boolean.class);
//如果该方法是类(即静态)方法,请在类上调用它:
调用(otherClass,false);
//如果该方法是实例(即非静态)方法,请在类的实例上调用它:
Object otherInstance=otherClass.newInstance();//获取其他类的实例-此方法假定存在默认构造函数
调用(otherInstance,false);

如果该类已初始化怎么办?我可以这样做吗?这不是有效的java代码,你到底想做什么?实际上,我试图使类简单化。这不是实际的类。(但它的行为应该相同)类主体中不能有代码,它不会编译。向我们展示你正在尝试做的事情的更现实的例子。
class_client.getDeclaredMethod("otherClass.someVoid",boolean.class);
Class<?> theOtherClazz = Class.forName("OtherClass");
Class<?> otherClass = Class.forName("com.xyz.OtherClass"); // Get the class
Method method = otherClass.getDeclaredMethod("someVoid", boolean.class);

// If the method is an Class (ie static) method, invoke it on the Class:
method.invoke(otherClass, false);

// If the method is an instance (ie non-static) method, invoke it on an instance of the Class:
Object otherInstance = otherClass.newInstance(); // Get an instance of other class - this approach assumes there is a default constructor
method.invoke(otherInstance, false);