Class.getDeclaredFields()和Class.getFields()的区别。 Class.getMethods()和Class.getDeclaredMethods()的区别。
package www.cn.extend; /** Animal * 2019/07/04 * @author Administrator * */ public class Animal { public String mName; public String mSex; private String mSecret = "I hava a secret but I can't tell you know"; public String getSecret() { return mSecret; } private void privateMethod() { System.out.println("just a privateMethod"); } }
package www.cn.extend; /** * Dog * @author Administrator * */ public class Dog extends Animal{ private String mJob; public String mSkill; protected String mDrive; int mAge; void keepFit(){ System.out.println(Dog.class.getSimpleName()+" to keepFit"); } private void sooEsad(){ System.out.println("asdf"); } }
package www.cn.extend; import java.lang.reflect.Method; public class Test { public static void main(String[] args){ /**.class.getFields(); * 返回父类和子类中公共属性的Field数组。 */ // Field[] fields = Dog.class.getFields(); // for (Field field:fields){ // System.out.println("this is a field from "+Dog.class.getSimpleName() +" : "+field); // } /**.class.getDeclaredFields(); * 返回子类中所有访问权限的属性。 */ // Field[] declaredFields = Dog.class.getDeclaredFields(); // for (Field field:declaredFields){ // System.out.println("this is a declaredFields from "+Dog.class.getSimpleName() +" : "+field); // } /**.class.getMethods(); * 返回父类的公共方法 */ // Method[] methods = Dog.class.getMethods(); // for (Method method:methods){ // System.out.println("this is a methods from "+Dog.class.getSimpleName() +" : "+method); // } /**.class.getDeclaredMethods(); * 返回子类所有权限的方法。 */ Method[] declaredMethods = Dog.class.getDeclaredMethods(); for (Method method:declaredMethods){ System.out.println(declaredMethods[0].getName()); System.out.println("this is a declaredMethods from "+Dog.class.getSimpleName() +" : "+method); } } }