Reputation: 3061
I need to find a list of the methods and public properties that are in an object dynamically. I will not have access to the class's definition. Is it possible to get a list of methods of an object given a reference to the object? If so, how?
Upvotes: 1
Views: 422
Reputation: 24910
java reflection api can do this for you.
http://download.oracle.com/javase/tutorial/reflect/class/classMembers.html
Upvotes: 2
Reputation: 3055
look here for a good introduction in java reflection:
http://tutorials.jenkov.com/java-reflection/index.html
With reflection you can get every method and object for a given class (next to many more features)
Upvotes: 1
Reputation: 1503429
You can get the class by calling getClass()
on the reference. From there, you can call getMethods(), getDeclaredMethods() etc. Sample code showing the methods in java.lang.String
:
import java.lang.reflect.Method;
public class Test {
public static void main(String[] args) {
showMethods("hello");
}
private static void showMethods(Object target) {
Class<?> clazz = target.getClass();
for (Method method : clazz.getMethods()) {
System.out.println(method.getName());
}
}
}
Look at the docs for Class
for more options of how to get methods etc.
Upvotes: 6