开发者

How to get a list of methods of an object or class?

开发者 https://www.devze.com 2023-03-17 19:31 出处:网络
I need to find a list of the methods and pu开发者_Go百科blic 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

I need to find a list of the methods and pu开发者_Go百科blic 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?


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.


java reflection api can do this for you.

http://download.oracle.com/javase/tutorial/reflect/class/classMembers.html


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)

0

精彩评论

暂无评论...
验证码 换一张
取 消