1. 基本概念
反射机制是 Java 提供的一种强大功能,允许程序在运行时查询和操作类的信息
- 首先获得这个对象对应的Class类的实例
- 因为Class这个类存储着一个类的所有信息:属性、方法、构造函数….所以我们可以通过Class类的实例来获取你想要调用的那个方法
- 拿到了对应的方法过后,我们可以给这个方法传入对应的参数来调用它。
2. 获取class
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
|
Class<MyClass> cls1 = MyClass.class;
访问某个类的class属性,这个属性就存储着这个类对应的Class类的实例: Class clz = com.axin.User.class;
MyClass obj = new MyClass(); Class<?> cls2 = obj.getClass();
调用某个对象的getClass()方法: Class clz = (new User()).getClass();
调用Class类的静态方法forName获取某个类的Class类实例: Class<?> cls3 = Class.forName("com.example.MyClass");
|
3. 获取类的信息
1 2 3 4
| Field[] fields = cls.getDeclaredFields(); for (Field field : fields) { System.out.println(field.getName()); }
|
4. 获取类的方法
1 2 3 4 5 6 7 8
| Method[] methods = cls.getDeclaredMethods(); for (Method method : methods) { System.out.println(method.getName()); }
Method method = clz.getMethod("setName", String.class);
|
5. 获取构造函数
1 2 3 4
| Constructor<?>[] constructors = cls.getDeclaredConstructors(); for (Constructor<?> constructor : constructors) { System.out.println(constructor.getName()); }
|
6. 操作字段
1 2 3 4 5 6 7 8 9 10 11 12
|
Field field = cls.getDeclaredField("myField"); field.setAccessible(true);
MyClass myObject = new MyClass(); Object value = field.get(myObject); field.set(myObject, newValue);
|
7. 操作方法
1 2 3 4 5 6 7 8 9 10 11
| Method method = cls.getDeclaredMethod("myMethod", String.class); method.setAccessible(true);
User user = new User(); method.invoke(user, "axin");
|