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));
}
}
// 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));
}
}