话不多说先上代码:
package Reflecthelper;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
/**
*
* @author Saturn
*
*/
class try1 { //测试的类
public void send(String send) {
System.out.println(send);
}
}
public class getMethod {
public static void main(String args[]) throws Exception {
Class<?> cls = try1.class;
Method methods[] = cls.getMethods();
for (Method met : methods) {
int mod = met.getModifiers();
System.out.print(Modifier.toString(mod) + " "); //先输出方法名字
System.out.print(met.getReturnType().getName() + " ");
System.out.print(met.getName() + "(");
Class<?> params[] = met.getParameterTypes();
for (int x = 0; x < params.length; x ++) {
System.out.print(params[x].getName() + " " + "args-" + x); //拼凑出方法要求的数据类型
if (x < params.length - 1) {
System.out.print(",");
}
}
System.out.print(") ");
Class<?> exp[] = met.getExceptionTypes();
if (exp.length > 0) {
System.out.print("throws "); //获取其支持处理的异常信息
}
for (int x = 0 ; x < exp.length ; x ++) {
System.out.print(exp[x].getName());
if (x < exp.length - 1) {
System.out.println(",");
}
}
System.out.println(); //换行
}
}
}
结果:
public void send(java.lang.String args-0) 下面的都是object中继承的方法
public final void wait(long args-0,int args-1) throws java.lang.InterruptedException
public final void wait() throws java.lang.InterruptedException
public final native void wait(long args-0) throws java.lang.InterruptedException
public boolean equals(java.lang.Object args-0)
public java.lang.String toString()
public native int hashCode()
public final native java.lang.Class getClass()
public final native void notify()
public final native void notifyAll()
原理:
通过反射机制获取类中的所有方法,随后将获取的所有方法对象中的信息拼凑输出。