Getting variables and methods of class from loaded class.
My scenario:
A class is going to be loaded from a number of different classes using ClassLoader.
How do I get the methods and variables from the class that loads开发者_StackOverflow another class - from the other class? I.e. getting methods and variables from a class I do not know the name of.
Example:
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
}
}
Searched stackoverflow but with no luck :/
Any help appreciated :).
Mike.
I'm not sure what your asking, but it sounds like you want the dynamically loaded class to have access to the fields and methods of the class containing the code from wich run()
was called. You can do this:
// you might need [2] in the following line
String callerClass = Thread.currentThread().getStackTrace()[1].getClassName();
This is the fully-qualified class name from which the current method was called. Once you have that, you can access the fields and methods of that class using reflection:
Class clazz = Class.forName(callerClass);
Field[] fields = clazz.getFields();
Method[] methods = clazz.getMethods();
If you want the non-accessible members as well, use getDeclaredFields()
and getDeclaredMethods()
.
For other ideas, take a look at this post.
I would do it in this way:
public class OtherClass {
public void run(Object invokerObject) {
Class invoker = invokerObject.getClass();
Field[] fields = invoker.getFields();
for (int i = 0; i < fields.length; i++) {
// retrieve info from fields[i] .
}
Method[] methods = invoker.getMethods();
for (int i = 0; i < methods.length; i++) {
// retrieve info from methods[i] .
}
}
}
This is accomplished via Reflection.
精彩评论