import java.lang.reflect.Field;
public class DemoFive {
public static void main(String[] args) throws NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException {
//创建一个Address对象
Address a= new Address();
//获取Address对应的class对象
Class c = Address.class;
//获取Address类的city属性,使用getDeclaredField()方法,表明可获取各种访问级别的属性
Field cityField = c.getDeclaredField("city");
//设置通过反射访问,该Field时取消权限检查
cityField.setAccessible(true);
//调用set方法为a对象的指定Field设置值
cityField.set(a,"襄阳");
//获取Address类的id属性,使用getDeclaredField()方法,表明可获取各种访问级别的属性
Field idField = c.getDeclaredField("id");
//设置通过反射访问,该Field时取消权限检查
idField.setAccessible(true);
//调用set方法为a对象的指定Field设置值
idField.set(a,20);
System.out.println(a);
}
public class DemoFive {
public static void main(String[] args) throws NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException {
//创建一个Address对象
Address a= new Address();
//获取Address对应的class对象
Class c = Address.class;
//获取Address类的city属性,使用getDeclaredField()方法,表明可获取各种访问级别的属性
Field cityField = c.getDeclaredField("city");
//设置通过反射访问,该Field时取消权限检查
cityField.setAccessible(true);
//调用set方法为a对象的指定Field设置值
cityField.set(a,"襄阳");
//获取Address类的id属性,使用getDeclaredField()方法,表明可获取各种访问级别的属性
Field idField = c.getDeclaredField("id");
//设置通过反射访问,该Field时取消权限检查
idField.setAccessible(true);
//调用set方法为a对象的指定Field设置值
idField.set(a,20);
System.out.println(a);
}
}
import java.lang.reflect.Array;
public class DemoSix {
public static void main(String[] args) {
//创建一个元素类型为String,长度为10的数组
Object arr = Array.newInstance(String.class,10);
//依次为arr数组中index为5,6的元素赋值
Array.set(arr,5,"Jack");
Array.set(arr,6,"John");
//依次取出arr数组中index为5.6的元素的值
Object o1 = Array.get(arr,5);
Object o2 = Array.get(arr,6);
//输出arr数组中index为5,6的元素
System.out.println(o1);
System.out.println(o2);
//动态创建数组和访问数组
}
}