用最简单直接的代码满足需求
话不多说,上代码,很简单,有几句注释看看就够了
首先随便建立个实体类
import java.util.List;
/**
* @author q3311
*
*/
public class People {
private int age;
private boolean sex;
private String name;
private List<String> sonName;
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public boolean isSex() {
return sex;
}
public void setSex(boolean sex) {
this.sex = sex;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public List<String> getSonName() {
return sonName;
}
public void setSonName(List<String> sonName) {
this.sonName = sonName;
}
}
然后是测试类,soeasy
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;
/**
* @author q3311
*
*/
public class ReflexTest {
public void process() {
People zhangsan = new People();
zhangsan.setAge(20);
zhangsan.setSex(true);
zhangsan.setName("xiaosan");
List<String> sonName = new ArrayList<String>();
sonName.add("haha");
sonName.add("hehe");
zhangsan.setSonName(sonName);
run(zhangsan);
}
public void run(Object obj) {
Field field;
try {
// 通过反射获得Zhangsan类中叫sonName的属性
field = obj.getClass().getDeclaredField("sonName");
// 设置外部可以访问
field.setAccessible(true);
// 得到这个对象的属性并且强转成list
List list = (List)field.get(obj);
for (int i = 0; i < list.size(); i++) {
System.out.println("list is:" + list.get(i));
}
// 清空field
field = null;
// 方法同上,此次得到的是String类型
field = obj.getClass().getDeclaredField("name");
field.setAccessible(true);
String string = field.get(obj).toString();
System.out.println("name is:" + string);
} catch (NoSuchFieldException | SecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static void main(String[] args) {
ReflexTest reflexTest = new ReflexTest();
reflexTest.process();
}
}