官方文档是这样说名的:
- getDeclaredMethod*获取的是类自身声明的所有方法,包含public、protected和private方法
- getMethod*获取的是类的所有共有方法,这就包括自身的所有public方法,和从基类继承的、从接口实现的所有public方法。
为了更好的说明,下面我们做个示例来验证,我们用getMethods方法来验证,而不是用getMethod方法来验证,getMethods方法能够打印出所有的方法,包括父类和当前类。
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
public class Teacher {
public String getName(String name, String address, Integer age) {
return name + "是一名人民教师,在"+address+","+age+"岁";
}
public static void main(String[] args) {
try {
Class<?> clazz = Class.forName("thread.Teacher");
Method[] methods = clazz.getMethods();
for(Method method:methods) {
String name = method.getName();
System.out.println(name);
}
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
打印结果是:
main
getName
wait
wait
wait
equals
toString
hashCode
getClass
notify
notifyAll