获取多重继承的母类和私有属性值

开发工具与关键技术:MyEclipse 10、java
作者:梁添荣
撰写时间:2019-07-08
该方法是获取一个类究竟多重继承了多少个类,并反射所有类的私有变量。

package com.gx.ts;

import java.lang.reflect.Field;
public class Test {
public static void main(String[] args) throws InstantiationException, IllegalAccessException {
getSon(Son.class);
}
//获取多重继承的母类
static void getSon(Class clas) throws InstantiationException, IllegalAccessException{
String name=clas.getName();//输出类名
System.out.println(name);
if(clas.getSuperclass()!=null){
getSon(clas.getSuperclass());
}
getVariable(clas);
}
//获取类的私有属性的值
static void getVariable(Class css) throws InstantiationException, IllegalAccessException{
Object object=css.newInstance();
Field[] field=object.getClass().getDeclaredFields();
for (Field field2 : field) {
field2.setAccessible(true);
Object object2=field2.get(object);
System.out.println(css+“的私有变量名:”+field2.getName()+“的值是:”+object2+"\r");
}
}
}
//设置祖、母、儿子关系的类
class GrandMother{
private String grandmother=“祖母”;
public String getGrandmother() {
return grandmother;
}
public void setGrandmother(String grandmother) {
this.grandmother = grandmother;
}
}
class Mother extends GrandMother{
private String mother=“母亲”;
public String getMother() {
return mother;
}
public void setMother(String mother) {
this.mother = mother;
}
}
class Son extends Mother{
private String son=“儿子”;
public String getSon() {
return son;
}
public void setSon(String son) {
this.son = son;
}
}

猜你喜欢

转载自blog.csdn.net/weixin_44619313/article/details/95043294
今日推荐