我可以获取一个类的所有方法吗?
假设我有一个.class文件,我可以得到该类中包含的所有方法吗?
直接从源代码: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 thisClass = DumpMethods.class;
Method[] methods = thisClass.getDeclaredMethods();
for (int i = 0; i < methods.length; i++) {
System.out.println(methods[i].toString());
}
} catch (Throwable e) {
System.err.println(e);
}
}
}
要了解所有方法,请在控制台中使用以下语句:
javap -cp jar-file.jar packagename.classname
或
javap class-file.class packagename.classname
或例如:
javap java.lang.StringBuffer