1.操作类
获取类,并通过反射获取一个实例对象
Class class1 = Student.class;
Student student = (Student)class1.newInstance(); //默认调用无参数的构造方法
student.setName("heh");
System.out.println(student.getName());
2.操作构造方法
获取指定参数类型的构造方法,通过此对象创建一个特定参数值的实例对象
Class class1 = Student.class;
Constructor<?> constructor = class1.getConstructor(String.class,String.class,int.class);
Student student1=(Student)constructor.newInstance("123","456",12);
System.out.println(student1.getAge());
3.操作普通方法
Class class1 = Student.class;
Student student=(Student)class1.newInstance();
Method method=class1.getMethod("setAge", int.class);
method.invoke(student,10);
System.out.println(student.getAge());
4.操作属性
Class class1 = Student.class;
Student student = (Student) class1.newInstance();
Field fiel=class1.getDeclaredField("age");
fiel.setAccessible(true); //AccessibleTest类中的成员变量为private,故必须进行此操作
fiel.set(student, 10);
System.out.println(student.getAge());
5.修改数组的值
int[] a= {1,2,3,4,5,6,7,8,9};
Class class1 = a.getClass().getComponentType(); //返回表示数组组件类型的 Class。如果此类不表示数组类,则此方法返回 null
System.out.println("数组数据的名称:"+class1.getName());
System.out.println("数组的长度:"+Array.getLength(a));
System.out.println("数据的第一个元素的值:"+Array.get(a,0));
Array.set(a, 0, 12);
System.out.println("数据的第一个元素的值:"+Array.get(a,0));