javase-反射字段学习记录

来源:互联网 发布:linux修改字符集为gbk 编辑:程序博客网 时间:2024/05/16 21:57
public class Demo5 {
// public String name="张三";
@Test
public void test1() throws ClassNotFoundException, NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException, InstantiationException{
Class clazz=Class.forName("cn.reflect.Person");
Person person=(Person) clazz.newInstance();
Field f= clazz.getField("name");
Object value=f.get(person);

Class type =f.getType();

if (type.equals(String.class)) {
String svalue = (String) value;
System.out.println(svalue);
}

//设置值
f.set(person, "xxxxxxxxxxxxxx");
System.out.println(person.name);

}

//private int password;
@Test
public void test2() throws ClassNotFoundException, NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException, InstantiationException{
Class clazz=Class.forName("cn.reflect.Person");
Person person = new Person();
Field f =clazz.getDeclaredField("password");
f.setAccessible(true);

System.out.println(f.get(person));
f.set(person, 423);
System.out.println(f.get(person));

}

// private static int age;
@Test
public void test3() throws ClassNotFoundException, NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException, InstantiationException{
Class clazz=Class.forName("cn.reflect.Person");
Person person = new Person();
Field f =clazz.getDeclaredField("age");
f.setAccessible(true);

System.out.println(f.get(null));
f.set(person, 423);
System.out.println(f.get(null));

}
}
0 0
原创粉丝点击