在此示例中,我们向您展示如何获取类对象中可用的方法。我们展示了三种获取方法的方法,它们是:
Class.getDeclaredMethods()
Class.getMethods()
Class.getMethod(String, Class<?>...)
package org.nhooo.example.lang;
import java.lang.reflect.Method;
public class GetMethods {
public static void main(String[] args) {
GetMethods object = new GetMethods();
Class clazz = object.getClass();
// 获取所有声明的方法,包括public,protected,private和
// 包(默认)访问权限,但不包括继承的方法。
Method[] methods = clazz.getDeclaredMethods();
for (Method method : methods) {
System.out.println("Method name = " + method.getName());
System.out.println("Method return type = " + method.getReturnType().getName());
Class[] paramTypes = method.getParameterTypes();
for (Class c : paramTypes) {
System.out.println("Param type = " + c.getName());
}
System.out.println("----------------------------------------");
}
System.out.println(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>");
//获取所有方法,包括继承的方法。使用getMethods()
// 我们只能访问公共方法。
methods = clazz.getMethods();
for (Method method : methods) {
System.out.println("Method name = " + method.getName());
System.out.println("Method return type = " + method.getReturnType().getName());
Class[] paramTypes = method.getParameterTypes();
for (Class c : paramTypes) {
System.out.println("Param type = " + c.getName());
}
System.out.println("----------------------------------------");
}
try {
// 我们还可以通过它们的名称和参数类型来获取方法,在这里我们
// 是tryinh来获取add(int,int)方法。
Method method = clazz.getMethod("add", new Class[] {int.class, int.class});
System.out.println("Method name: " + method.getName());
} catch (NoSuchMethodException e) {
e.printStackTrace();
}
}
public int add(int numberA, int numberB) {
return numberA + numberB;
}
protected int multiply(int numberA, int numberB) {
return numberA * numberB;
}
private double div(int numberA, int numberB) {
return numberA / numberB;
}
}