java从加载的类中获取类的变量和方法。
我的设想:
将使用ClassLoader从多个不同的类中加载一个类
如何从加载另一个类的类(从另一个类)中获取方法和变量?例如,从一个我不知道名称的类中获取方法和变量
例如:
public class MainClass {
public static String str = "hey";
public static void main(String[] args) {
//load the OtherClass class, create an instance of it, and invoke its run method
}
}
public class OtherClass {
public void run() {
//get all variables of the class that instantialized the class
}
}
搜索堆栈溢出但没有运气:/
感谢您的帮助:)
迈克
# 1 楼答案
这是通过Reflection实现的
# 2 楼答案
我会这样做:
# 3 楼答案
我不确定您的要求是什么,但听起来您希望动态加载的类能够访问包含调用
run()
代码的类的字段和方法。您可以这样做:这是调用当前方法的完全限定类名。一旦具备了该功能,就可以使用反射访问该类的字段和方法:
如果还需要不可访问的成员,请使用
getDeclaredFields()
和getDeclaredMethods()
有关其他想法,请参阅this post