我可以获得课程的所有方法吗?

时间:2011-03-10 22:10:15

标签: java class methods

假设我有一个.class文件,我可以获得该类中包含的所有方法吗?

5 个答案:

答案 0 :(得分:57)

直接来源:http://java.sun.com/developer/technicalArticles/ALT/Reflection/ 然后我将其修改为自包含,不需要命令行中的任何内容。 ; - )

import java.lang.reflect.*;

/** 
Compile with this:
C:\Documents and Settings\glow\My Documents\j>javac DumpMethods.java

Run like this, and results follow
C:\Documents and Settings\glow\My Documents\j>java DumpMethods
public void DumpMethods.foo()
public int DumpMethods.bar()
public java.lang.String DumpMethods.baz()
public static void DumpMethods.main(java.lang.String[])
*/

public class DumpMethods {

    public void foo() { }

    public int bar() { return 12; }

    public String baz() { return ""; }

    public static void main(String args[])
    {
        try {
            Class c = DumpMethods.class;
            Method[] m = c.getDeclaredMethods();
            for (int i = 0; i < m.length; i++)
            System.out.println(m[i].toString());
        } catch (Throwable e) {
            System.err.println(e);
        }
    }
}

答案 1 :(得分:28)

要了解所有方法,请在控制台中使用此语句:

javap java.packagename.classname

示例:javap java.lang.StringBuffer

答案 2 :(得分:8)

public static Method[] getAccessibleMethods(Class clazz) {
    List<Method> result = new ArrayList<Method>();
    while (clazz != null) {
        for (Method method : clazz.getDeclaredMethods()) {
            int modifiers = method.getModifiers();
            if (Modifier.isPublic(modifiers) || Modifier.isProtected(modifiers)) {
                result.add(method);
            }
        }
        clazz = clazz.getSuperclass();
    }
    return result.toArray(new Method[result.size()]);
}

答案 3 :(得分:4)

您可以使用Reflection API

答案 4 :(得分:2)

package tPoint;

import java.io.File;
import java.lang.reflect.Method;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;

public class ReadClasses {

public static void main(String[] args) {

    try {
        Class c = Class.forName("tPoint" + ".Sample");
        Object obj = c.newInstance();
        Document doc = 
        DocumentBuilderFactory.newInstance().newDocumentBuilder()
                .parse(new File("src/datasource.xml"));

        Method[] m = c.getDeclaredMethods();

        for (Method e : m) {
            String mName = e.getName();
            if (mName.startsWith("set")) {
                System.out.println(mName);
                e.invoke(obj, new 
          String(doc.getElementsByTagName(mName).item(0).getTextContent()));
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}

}