package com.demo.zhengweiTest;
/**
* Created by zhengwei.wzw on 2015/7/22.
*/
public class Animal {
protected String type;
}
package com.demo.zhengweiTest;
/**
* Created by zhengwei.wzw on 2015/7/22.
*/
public class People extends Animal{
protected String name;
}
package com.demo.zhengweiTest;
/**
* Created by zhengwei.wzw on 2015/7/22.
*/
public class Student extends People {
protected int score;
public String toString(){
String toString="type:"+type+" name:"+name+" score:"+score;
System.out.println(toString);
return toString;
}
}
package com.demo.zhengweiTest;
import java.lang.reflect.Field;
/**
* Created by zhengwei.wzw on 2015/7/22.
*/
public class Test {
public static void main(String args[])throws Exception{
Class clazz=Class.forName("com.demo.zhengweiTest.Student");
Student stu=(Student)clazz.newInstance();
Field typeField=null,nameField=null,scoreField=null;
for(;clazz != Object.class;clazz= clazz.getSuperclass()){
System.out.println(clazz+" begin");
try{
typeField = clazz.getDeclaredField("type");
if(typeField!=null)
System.out.println(typeField.getName());
}catch(Exception e){}
try {
nameField = clazz.getDeclaredField("name");
if(nameField!=null)
System.out.println(nameField.getName());
} catch (Exception e) {}
try {
scoreField = clazz.getDeclaredField("score");
if(scoreField!=null)
System.out.println(scoreField.getName());
} catch (Exception e) {}
System.out.println(clazz+" end");
}
if(typeField!=null){
typeField.setAccessible(true);
typeField.set(stu,"人类");
}
if(nameField!=null){
nameField.setAccessible(true);
nameField.set(stu,"xiao li");
}
if(scoreField!=null){
scoreField.setAccessible(true);
scoreField.setInt(stu, 88);
}
stu.toString();
}
}
输出:
class com.demo.zhengweiTest.Student begin
score
class com.demo.zhengweiTest.Student end
class com.demo.zhengweiTest.People begin
name
class com.demo.zhengweiTest.People end
class com.demo.zhengweiTest.Animal begin
type
class com.demo.zhengweiTest.Animal end
type:人类 name:xiao li score:88
Process finished with exit code 0
使用反射获取父类的属性并设值,适用于类中没有提供setter方法
最新推荐文章于 2022-02-24 17:28:38 发布