本文主要是介绍Java中Class的getDeclaredMethods和getMethods的区别,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
在实际中经常需要使用反射机制获取类的属性和方法等信息.
Class中有两个方法可以获取类的方法:getDeclaredMethods和getMethods
下面实例说明这两个的区别
创建person类
class person{private float height;private float weight;void getPersonName() {}public void getPersonHeight() {}private void getPersonWeight() {}protected void getPersonColor() {}
}
创建person类的子类
class student extends person {private String name;private int age;public student() {super();}void getStudentHeight() {} public void getStudentName() {} private void getStudentAge() {}protected void getStudentColor() {}
}
测试
public class reflect {public static void main(String[] args) { try {Class classzz = Class.forName("student");System.out.println("classzz = " + classzz);//getMethods方法Method[] methods = classzz.getMethods();System.out.println(" ----getMethods: ");for(Method m : methods) {System.out.println(m);}//getDeclaredMethods 方法Method[] declaredMethods = classzz.getDeclaredMethods();System.out.println("\r\n ----declaredMethods: ");for(Method m : declaredMethods) {System.out.println(m);} } catch (ClassNotFoundException e) {// TODO Auto-generated catch blocke.printStackTrace();} }
}
输出
classzz = class student----getMethods:
public void student.getStudentName()
public void person.getPersonHeight()
public final void java.lang.Object.wait(long,int) throws java.lang.InterruptedException
public final void java.lang.Object.wait() throws java.lang.InterruptedException
public final native void java.lang.Object.wait(long) throws java.lang.InterruptedException
public boolean java.lang.Object.equals(java.lang.Object)
public java.lang.String java.lang.Object.toString()
public native int java.lang.Object.hashCode()
public final native java.lang.Class java.lang.Object.getClass()
public final native void java.lang.Object.notify()
public final native void java.lang.Object.notifyAll()----declaredMethods:
void student.getStudentHeight()
public void student.getStudentName()
private void student.getStudentAge()
protected void student.getStudentColor()
总结
- 从以上测试结果可以看出,declaredMethods只能获取当前类的方法(包访问权限+public + private + protcted).
- getMethods可以获取本身类和其**所有父类的所有共有方法(public)**.
这篇关于Java中Class的getDeclaredMethods和getMethods的区别的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!