参考:https://www.cnblogs.com/chanshuyi/p/head_first_of_reflection.html
正射与反射
一般情况下,我们使用某个类时必定知道它是什么类,是用来做什么的。于是我们直接对这个类进行实例化,之后使用这个类对象进行操作。
1 2
| Apple apple = new Apple(); apple.setPrice(4);
|
上面这样子进行类对象的初始化,我们可以理解为「正」。
而反射则是一开始并不知道我要初始化的类对象是什么,自然也无法使用 new 关键字来创建对象了。
这时候,我们使用 JDK 提供的反射 API 进行反射调用:
1 2 3 4 5
| Class clz = Class.forName("com.chenshuyi.reflect.Apple"); Method method = clz.getMethod("setPrice", int.class); Constructor constructor = clz.getConstructor(); Object object = constructor.newInstance(); method.invoke(object, 4);
|
两段代码的结果一样,但是思路不一样,第一个在未运行时就确定了要运行的类apple,第二个则是在运行时通过字符串值才得知要运行的类(com.chenshuyi.reflect.Apple)。
总的来说,反射就是在运行时才知道要操作的类是什么,并且可以在运行时获取类的完整构造,并调用对应的方法。
反射用例
完整的反射例子如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
| public class Apple {
private int price;
public int getPrice() { return price; }
public void setPrice(int price) { this.price = price; }
public static void main(String[] args) throws Exception{ Apple apple = new Apple(); apple.setPrice(5); System.out.println("Apple Price:" + apple.getPrice()); Class clz = Class.forName("com.chenshuyi.api.Apple"); Method setPriceMethod = clz.getMethod("setPrice", int.class); Constructor appleConstructor = clz.getConstructor(); Object appleObj = appleConstructor.newInstance(); setPriceMethod.invoke(appleObj, 14); Method getPriceMethod = clz.getMethod("getPrice"); System.out.println("Apple Price:" + getPriceMethod.invoke(appleObj)); } }
|
输出为:
1 2
| Apple Price:5 Apple Price:14
|
反射的基本步骤
1
| Class clz = Class.forName("com.zhenai.api.Apple");
|
- 根据 Class 对象实例获取 Constructor 对象
1
| Constructor appleConstructor = clz.getConstructor();
|
- 使用 Constructor 对象的 newInstance 方法获取反射类对象
1
| Object appleObj = appleConstructor.newInstance();
|
而如果要调用某一个方法,则需要经过下面的步骤:
1
| Method setPriceMethod = clz.getMethod("setPrice", int.class);
|
1
| setPriceMethod.invoke(appleObj, 14);
|
反射的api都有哪些
有这几类api:获取反射的 Class 对象、通过反射创建类对象、通过反射获取类属性、方法及构造器
1. 获取反射中的Class对象
类对象: 所有的类,都存在一个类对象,这个类对象用于提供类本身的信息,比如有几种构造方法, 有多少属性,有哪些普通方法。
在 Java API 中,获取 Class 类对象有三种方法:
**第一种,使用 Class.forName 静态方法。**当你知道该类的全路径名时,你可以使用该方法获取 Class 类对象。
1
| Class clz = Class.forName("java.lang.String");
|
第二种,使用 .class 方法。
这种方法只适合在编译前就知道操作的 Class。
1
| Class clz = String.class;
|
第三种,使用类对象的 getClass() 方法。
1 2
| String str = new String("Hello"); Class clz = str.getClass();
|
在一个JVM中,一种类,只会有一个类对象存在。所以以上三种方式取出来的类对象,都是一样的。
2. 通过反射创建类对象
通过反射创建类对象主要有两种方式:通过 Class 对象的 newInstance() 方法、通过 Constructor 对象的 newInstance() 方法。
第一种:通过 Class 对象的 newInstance() 方法。
1 2
| Class clz = Apple.class; Apple apple = (Apple)clz.newInstance();
|
第二种:通过 Constructor 对象的 newInstance() 方法
1 2 3
| Class clz = Apple.class; Constructor constructor = clz.getConstructor(); Apple apple = (Apple)constructor.newInstance();
|
通过 Constructor 对象创建类对象可以选择特定构造方法,而通过 Class 对象则只能使用默认的无参数构造方法。下面的代码就调用了一个有参数的构造方法进行了类对象的初始化。
1 2 3
| Class clz = Apple.class; Constructor constructor = clz.getConstructor(String.class, int.class); Apple apple = (Apple)constructor.newInstance("红富士", 15);
|
3.通过反射获取类属性
我们通过 Class 对象的 getFields() 方法可以获取 Class 类的属性,但无法获取私有属性。
1 2 3 4 5
| Class clz = Apple.class; Field[] fields = clz.getFields(); for (Field field : fields) { System.out.println(field.getName()); }
|
输出结果是:
而如果使用 Class 对象的 getDeclaredFields() 方法则可以获取包括私有属性在内的所有属性:
1 2 3 4 5
| Class clz = Apple.class; Field[] fields = clz.getDeclaredFields(); for (Field field : fields) { System.out.println(field.getName()); }
|
输出结果是:
与获取类属性一样,当我们去获取类方法、类构造器时,如果要获取私有方法或私有构造器,则必须使用有 declared 关键字的方法。
4. 通过反射获取类构造器
非私有构造器
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
| import java.lang.reflect.Constructor;
public class ReflectionExample { public static void main(String[] args) { try { Class<?> clazz = Class.forName("com.example.MyClass");
Constructor<?> constructor = clazz.getConstructor();
Constructor<?> constructorWithParams = clazz.getConstructor(String.class, int.class);
System.out.println("无参构造器: " + constructor); System.out.println("带参数构造器: " + constructorWithParams);
Object instance = constructor.newInstance(); System.out.println("通过无参构造器创建的对象: " + instance);
Object instanceWithParams = constructorWithParams.newInstance("Hello", 42); System.out.println("通过带参数构造器创建的对象: " + instanceWithParams);
} catch (Exception e) { e.printStackTrace(); } } }
|
私有构造器
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
| import java.lang.reflect.Constructor;
public class PrivateConstructorExample { public static void main(String[] args) { try { Class<?> clazz = Class.forName("com.example.MyPrivateClass");
Constructor<?> privateConstructor = clazz.getDeclaredConstructor();
privateConstructor.setAccessible(true);
Object instance = privateConstructor.newInstance();
System.out.println("通过私有构造器创建的对象: " + instance);
} catch (Exception e) { e.printStackTrace(); } } }
|
5. 通过反射获取类方法
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35
| import java.lang.reflect.Method;
public class ReflectionMethodExample { public static void main(String[] args) { try { Class<?> clazz = Class.forName("com.example.MyClass");
Method publicMethod = clazz.getMethod("publicMethod", String.class, int.class);
Method privateMethod = clazz.getDeclaredMethod("privateMethod", String.class);
privateMethod.setAccessible(true);
Object instance = clazz.newInstance();
Object resultPublic = publicMethod.invoke(instance, "Hello", 123);
Object resultPrivate = privateMethod.invoke(instance, "Hello");
System.out.println("公共方法调用结果: " + resultPublic); System.out.println("私有方法调用结果: " + resultPrivate);
} catch (Exception e) { e.printStackTrace(); } } }
|
哪些地方用到了反射
例如我们经常使用的 Spring 配置中,经常会有相关 Bean 的配置:
1 2
| <bean class="com.chenshuyi.Apple"> </bean>
|
当我们在 XML 文件中配置了上面这段配置之后,Spring 便会在启动的时候利用反射去加载对应的 Apple 类。而当 Apple 类不存在或发生启发异常时,异常堆栈便会将异常指向调用的 invoke 方法。