一、获取Class对象
方法1:通过Class类的静态方法 forName()
Class<?> myclass = Class.forName("packageName.Student");
方法2:通过类名.class
Class<Student> myclass = Student.class;
方法3:通过对象.getClass()
Student student = new Student();
Class<? extends Student> myclass = student.getClass();
二、创建对象
方法1:通过Class对象的 newInstance() 方法
Object obj = myclass.newInstance();
方法2:先获取构造方法,再用构造方法创建对象
Constructor<?> constructor = myclass.getConstructor();
Object obj = constructor.newInstance();
三、获取成员变量
获取单个成员变量
getField():获取该类的 public 成员变量,包括继承而来的
getDeclaredField():获取该类定义的成员变量,包括私有,但不包括继承而来的
Field field = myclass.getField("变量名");
Field field = myclass.getDeclaredField("变量名");
获取成员变量数组
getFields():获取该类的所有 public 成员变量,包括继承而来的
getDeclaredFields():获取该类定义的所有成员变量,包括私有,但不包括继承而来的
Field[] fields = myclass.getFields();
Field[] fields = myclass.getDeclaredFields();
四、获取方法
获取单个方法
getMethod():获取该类的 public 方法,包括继承而来的
getDeclaredMethod():获取该类定义的方法,包括私有,但不包括继承而来的
Method method = myclass.getMethod();
Method method = myclass.getDeclaredMethod();
获取方法数组
getMethods():获取该类的所有 public 方法,包括继承而来的
getDeclaredMethods():获取该类定义的所有方法,包括私有,但不包括继承而来的
Method[] methods = myclass.getMethods();
Method[] methods = myclass.getDeclaredMethods();
五、访问私有变量或方法
私有变量或私有方法对象的 setAccessible(true) 方法设置为true,代表压制Java访问检查,否则会出 IllegalAccessException 非法访问异常
field.setAccessible(true);
method.setAccessible(true);
六、变量获取值与设置值
Object get(Object obj) :获取值
void set(Object obj, Object value) :设置值
String name = (String) field.get("name");
field.set(obj, "小明");
七、调用方法
Object invoke(Object obj, Object… args) :通过方法对象调用 invoke() 方法,传入对象实例与参数
method.invoke(obj);
反射基本用法示例
一个学生类 Student
public class Student {
private String name; //私有变量,反射操作时需打开访问权限才能赋值
private String sid;
public Student() {
}
public Student(String name) {
this.name = name;
}
public void read() {
System.out.println("学生:" + name + ",学号:" + sid + ",正在看书...");
}
}
配置文件 props.properties
className=package_210924.Student
methodName=read
fieldName=sid
主类
public class ReflectDemo {
public static void main(String[] args) throws Exception {
//创建properties对象
Properties prop = new Properties();
//获取Classloader
ClassLoader classLoader = ReflectDemo.class.getClassLoader();
//通过classloader加载配置文件的输入流
InputStream is = classLoader.getResourceAsStream("package_210924\\props.properties");
//properties对象加载该输入流
prop.load(is);
//获取配置数据
String className = prop.getProperty("className");
String methodName = prop.getProperty("methodName");
String fieldName = prop.getProperty("fieldName");
is.close();
//获取类
Class<?> class1 = Class.forName(className);
//获取构造方法
Constructor<?> constructor = class1.getConstructor(String.class);
//用构造方法创建对象
Object obj = constructor.newInstance("小明");
//获取姓名字段并设置值
Field field = class1.getDeclaredField(fieldName);
field.setAccessible(true); //对私有成员变量设置访问权限
field.set(obj, "stu001");
//获取方法对象
Method method = class1.getDeclaredMethod(methodName);
//调用方法
method.invoke(obj);
}
}
输出结果