1. 通过反射获取构造方法、成员变量、成员方法
2. 形参的可变参数
3. 反射中私有方法调用注意事项
4. 反射中静态变量及方法调用注意事项
package com.homework.classtest;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
/**
* @Author jinman1012@qq.com 2020/8/8 17:00
* @Version 1.0
*/
public class CommonTest {
public static void main(String[] args) throws NoSuchFieldException, NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException {
//获取Student对象的Class对象
Class clz = Student.class;
//获取构造方法
Constructor dc = clz.getDeclaredConstructor(int.class, double.class, String.class);
//实例化Student对象
Student stu = (Student)dc.newInstance(25, 180.0, "李四");
Method studyOne = clz.getDeclaredMethod("study", String.class,int[].class);
Method studyTwo = clz.getDeclaredMethod("study", String[].class);
studyOne.setAccessible(true);
studyTwo.setAccessible(true);
studyOne.invoke(stu,"gg",new int[]{2,12,8,9});
studyTwo.invoke(null,new Object[]{new String[]{"夕阳红","真不错,住山里真不错","CSGO磨刀石"}});
//获取Studeng类的成员变量
Field age = clz.getDeclaredField("age");
Field heigt = clz.getDeclaredField("heigt");
Field name = clz.getDeclaredField("name");
//绕过JVM权限检测
name.setAccessible(true);
int getAgeValue = (int)age.get(stu);
//静态成员变量传入任意对象都可getValue
double getHeighValue1 = (double)heigt.get(stu);
double getHeighValue2 = (double)heigt.get(null);
double getHeighValue3 = (double)heigt.get("");
double getHeighValue4 = (double)heigt.get(new String());
//不加setAccessible(true)会报java.lang.IllegalAccessException
String getNameValue = (String)name.get(stu);
System.out.println(getAgeValue);
System.out.println(getHeighValue1);
System.out.println(getHeighValue2);
System.out.println(getHeighValue3);
System.out.println(getHeighValue4);
System.out.println(getNameValue);
}
}
//测试类
class Student {
int age;
static double heigt;
private String name;
public Student(int age, double heigt, String name) {
this.age = age;
this.heigt = heigt;
this.name = name;
}
private void study(String name,int... arr) {
System.out.println(name + "I'm studying.");
int sum = 0;
for (int i = 0; i < arr.length; i++) {
sum += arr[i];
}
System.out.println(name + "I'm calculating" + sum);
}
private static void study(String... habits) {
System.out.println("爱好:");
for (int i = 0; i < habits.length; i++) {
System.out.print(habits[i] + " ");
}
}
}