------------------------------------------------------------------------
操作步骤:
1、加载类,如Class cla=Person.class
2、调用getField()/getDeclaredField()方法,参数是类的成员方法名称,如
Filed Field f=cla.getDeclaredField("password");
3、调用System.out.println(f.get(p));
--------------------------------------------------------------------------------
例子:
public class Person {
public String name="qq";
private int password=23;
private static int age=345;
-----------------------------------------------------
测试类:
public class Demo2 {
Person p = new Person();
@Test
public void demotest() throws Throwable, SecurityException {
Class cla = Person.class;
Field f=cla.getField("name");
//获取字段的值
Object value=f.get(p);
//获取字段的类型
Class type =f.getType();
if(type.equals(String.class)){
String svalue=(String)value;
System.out.println(svalue);
}
//设置字段的值
f.set(p,"你好");
System.out.println(p.name);
}
@Test
public void demotest2() throws Throwable, SecurityException {
Class cla = Person.class;
Field f=cla.getDeclaredField("password");
f.setAccessible(true);
System.out.println(f.get(p));
}
}