java之通过反射,来获得某对象的所有方法(类方法提取器)

时间:2021-11-03 15:31:58

参考Thinging in Java

在编程时, 如果不记得一个类是否有某个方法,或者不知道一个类究竟能做些什么,而又不想通过索引或 类的层次结构去查找jdk文档,这时通过反射的小工具能节省很多时间。

浏览实现了类定义的源代码或是其jdk文档,只能找到在 这个类定义中 被定义或被覆盖的方法。但,对你来说,可能有数十个更有用的方法都是继承自 基类的。要找出 这些方法,可能会很乏味而且费时间。幸运的是,反射机制 提供了一种方法,使我们能够编写可以自动展示接口的简单工具。

下面就是其工作方式:

package com.westward;

import java.lang.reflect.Constructor;
import java.lang.reflect.Method;
import java.util.regex.Pattern; public class ShowMethods { private static String usage=
"usage:\n" +
"ShowMethods qualified.class.name\n"+
"To show all methods in class or:\n"+
"ShowMethods qualified.class.name word\n"+
"To search for methods involving 'word'";
private static Pattern p= Pattern.compile("\\w+\\.");
public static void main(String[] args) {
if (args.length<1) {
System.out.println(usage);
System.exit(0);
}
int lines= 0;
try {
Class<?> c= Class.forName(args[0]);
Method[] methods= c.getMethods();
Constructor[] ctors= c.getConstructors();
if (args.length==1) {
for (Method method : methods) {
System.out.println(p.matcher(method.toString()).replaceAll(""));
System.out.println(method);
}
for (Constructor ctor : ctors) {
System.out.println(p.matcher(ctor.toString()).replaceAll(""));
System.out.println(ctor);
}
lines= methods.length+ ctors.length;
}else {
for (Method method : methods) {
if (method.toString().indexOf(args[1]) != -1) {
System.out.println(p.matcher(method.toString()).replaceAll(""));
System.out.println(method);
lines++;
}
}
for (Constructor ctor : ctors) {
if (ctor.toString().indexOf(args[1]) != -1) {
System.out.println(p.matcher(ctor.toString()).replaceAll(""));
System.out.println(ctor);
lines++;
}
}
}
} catch (ClassNotFoundException e) {
System.out.println("No such class: " + e);
}
} }

input:com.westward.ShowMethods

output:
public static void main(String[])
public static void com.westward.ShowMethods.main(java.lang.String[])
public final void wait(long,int) throws InterruptedException
public final void java.lang.Object.wait(long,int) throws java.lang.InterruptedException
public final native void wait(long) throws InterruptedException
public final native void java.lang.Object.wait(long) throws java.lang.InterruptedException
public final void wait() throws InterruptedException
public final void java.lang.Object.wait() throws java.lang.InterruptedException
public boolean equals(Object)
public boolean java.lang.Object.equals(java.lang.Object)
public String toString()
public java.lang.String java.lang.Object.toString()
public native int hashCode()
public native int java.lang.Object.hashCode()
public final native Class getClass()
public final native java.lang.Class java.lang.Object.getClass()
public final native void notify()
public final native void java.lang.Object.notify()
public final native void notifyAll()
public final native void java.lang.Object.notifyAll()
public ShowMethods()
public com.westward.ShowMethods()