目录
1、提出问题:
2、测试Demo:
3、源码
3/1 getMethods()方法
3/2 getDeclaredClasses()方法
1、提出问题:
Class.getMethods() 和 Class.getDeclaredMethods()区别是什么?获取到哪些返回值?
2、测试Demo:
public class test_class_extends_static_function_polymorphic {
public static void main(String[] args) {
// TODO Auto-generated method stub
try {
Class c=Class.forName("C");
Method[] methods = c.getMethods();
for(int i=0;i<methods.length;i++) {
System.out.println(methods[i]);
}
System.out.println("====");
Method[] declaredMethods = c.getDeclaredMethods();
for(int i=0;i<declaredMethods.length;i++) {
System.out.println(declaredMethods[i]);
}
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
class C{
public static void C(){}
private static void B(){}
}
console:
public static void C.C()
public final void java.lang.Object.wait(long,int) throws java.lang.InterruptedException
public final native void java.lang.Object.wait(long) throws java.lang.InterruptedException
public final void java.lang.Object.wait() 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()
====
private static void C.B()
public static void C.C()
总结:
1)getDeclaredClasses():获取的是所有定义的方法;
* @return the array of {@code Class} objects representing all the
* declared members of this class
2)getMethods():获取的是所有public修饰符权限的方法;
* @return the array of {@code Method} objects representing the
* public methods of this class
3、源码
3/1 getMethods()方法
@CallerSensitive
public Method[] getMethods() throws SecurityException {
checkMemberAccess(Member.PUBLIC, Reflection.getCallerClass(), true);
return copyMethods(privateGetPublicMethods());
}
可以看到:Member.PUBLIC;这个是Membet 接口定义的常量:
/**
* Identifies the set of all public members of a class or interface,
* including inherited members.
*/
public static final int PUBLIC = 0;
3/2 getDeclaredClasses()方法
@CallerSensitive
public Class<?>[] getDeclaredClasses() throws SecurityException {
checkMemberAccess(Member.DECLARED, Reflection.getCallerClass(), false);
return getDeclaredClasses0();
}
可以看到:Member.PUBLIC;同样也是Membet 接口定义的常量:
/**
* Identifies the set of declared members of a class or interface.
* Inherited members are not included.
*/
public static final int DECLARED = 1;