子类是否可以通过反射得到父类的私有方法
答案是可以。
一次电话面试中被问到这个问题,当时答错了,现在记录一下。
测试类如下:
@Test
public void test07() {
Father father = new Father();
Class<? extends Father> fatherClass = father.getClass();
Field[] fields = fatherClass.getFields();// 只能得到public属性
System.out.println(fields);
Field[] declaredFieldsFather = fatherClass.getDeclaredFields();
System.out.println(declaredFieldsFather);// 可以得到private default protected public属性
Son son = new Son();
Class<? extends Son> sonClass = son.getClass();
Field[] fieldsSon = sonClass.getFields();// 得到父类的public属性和自己的public属性
System.out.println(fieldsSon);
Field[] declaredFieldsSon = sonClass.getDeclaredFields();// 得到子类自己的所有范围属性,得不到父类的任何属性
// 通过这种方法可以得到父类的所有属性 -→ 先得到父类class 然后class调用getDeclaredFields()方法
Class<?> superclass = sonClass.getSuperclass();
Field[] declaredFields = superclass.getDeclaredFields();
System.out.println(declaredFieldsSon);
GrandSon grandSon = new GrandSon();//孙子
Class<? extends GrandSon> classGrandSon = grandSon.getClass();
Field[] fieldsGrandSon = classGrandSon.getFields();//得到孙子的公共属性
Field[] declaredGrandSon = classGrandSon.getDeclaredFields();//得到孙子的所有属性,得不到孙子父类的属性
Field[] declaredFields2 = classGrandSon.getSuperclass().getSuperclass().getDeclaredFields();//得到Father类的所有属性,也就是爷爷
}
附上父类和子类和孙子类代码
父类
@Getter
@Setter
@ToString
public class Father {
private String fatherName;
private String fatherAge;
protected String fatherMobile;
String address;
Integer height;
public boolean isWorker;
private String getFood() {
return "getFood";
}
Integer getAge() {
return 0;
}
public void eat() {
System.out.println("eat");
}
}
子类
@Getter
@Setter
@ToString
public class Son extends Father {
private String sonName;
private String sonAge;
protected String sonMobile;
Integer monthSalary;
public boolean isWorker;
private String getName() {
return "getName";
}
public void play() {
System.out.println("play");
}
}
孙子类
@Getter
@Setter
@ToString
public class GrandSon extends Son{
private String grandSonName;
protected String grandSonAge;
}
getClass()返回的是这个
另外,有的项目里的基类就是把一些公共属性放在基类里,然后有需要的类可以继承基类,这样 有需要的类即有了基类(父类)的属性,也有了自己的属性。