一起养成写作习惯!这是我参与「掘金日新计划 · 4 月更文挑战」的第19天,点击查看活动详情。
class对象动态生成
//第一种方式 Class对象调用newInstance()方法生成
Object obj = class1.newInstance();
//第二种方式 对象获得对应的Constructor对象,再通过该Constructor对象的newInstance()方法生成
Constructor<?> constructor = class1.getDeclaredConstructor(new Class[]{String.class});//获取指定声明构造函数
obj = constructor.newInstance(new Object[]{"lcj"});
动态调用函数
try {
// 生成新的对象:用newInstance()方法
Object obj = class1.newInstance();
//判断该对象是否是Person的子类
boolean isInstanceOf = obj instanceof Person;
//首先需要获得与该方法对应的Method对象
Method method = class1.getDeclaredMethod("setAge", new Class[]{int.class});
//调用指定的函数并传递参数
method.invoke(obj, 28);
method = class1.getDeclaredMethod("getAge");
Object result = method.invoke(obj, new Class[]{});
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
通过反射机制获取泛型类型
例如下面这种结构
//People类
public class People<T> {}
//Person类继承People类
public class Person<T> extends People<String> implements PersonInterface<Integer> {}
//PersonInterface接口
public interface PersonInterface<T> {}
获取泛型类型
Person<String> person = new Person<>();
//第一种方式 通过对象getClass方法
Class<?> class1 = person.getClass();
Type genericSuperclass = class1.getGenericSuperclass();//获取class对象的直接超类的 Type
Type[] interfaceTypes = class1.getGenericInterfaces();//获取class对象的所有接口的Type集合
getComponentType(genericSuperclass);
getComponentType(interfaceTypes[0]);
getComponentType具体实现
private Class<?> getComponentType(Type type) {
Class<?> componentType = null;
if (type instanceof ParameterizedType) {
//getActualTypeArguments()返回表示此类型实际类型参数的 Type 对象的数组。
Type[] actualTypeArguments = ((ParameterizedType) type).getActualTypeArguments();
if (actualTypeArguments != null && actualTypeArguments.length > 0) {
componentType = (Class<?>) actualTypeArguments[0];
}
} else if (type instanceof GenericArrayType) {
// 表示一种元素类型是参数化类型或者类型变量的数组类型
componentType = (Class<?>) ((GenericArrayType) type).getGenericComponentType();
} else {
componentType = (Class<?>) type;
}
return componentType;
}
通过反射机制获取注解信息
这里重点以获取Method的注解信息为例
try {
//首先需要获得与该方法对应的Method对象
Method method = class1.getDeclaredMethod("jumpToGoodsDetail", new Class[]{String.class, String.class});
Annotation[] annotations1 = method.getAnnotations();//获取所有的方法注解信息
Annotation annotation1 = method.getAnnotation(RouterUri.class);//获取指定的注解信息
TypeVariable[] typeVariables1 = method.getTypeParameters();
Annotation[][] parameterAnnotationsArray = method.getParameterAnnotations();//拿到所有参数注解信息
Class<?>[] parameterTypes = method.getParameterTypes();//获取所有参数class类型
Type[] genericParameterTypes = method.getGenericParameterTypes();//获取所有参数的type类型
Class<?> returnType = method.getReturnType();//获取方法的返回类型
int modifiers = method.getModifiers();//获取方法的访问权限
} catch (NoSuchMethodException e) {
e.printStackTrace();
}
反射机制的优缺点及应用场景
优点
- 反射提高了程序的灵活性与扩展性。
- 降低耦合性,提高自适应能力。
- 它允许程序创建和控制任何类的对象,无需提前硬编码目标类。
缺点
- 性能问题:使用反射基本上是一种解释操作,用于字段和方法接入时要远慢于直接代码。因此反射机制主要应用在对灵活性和拓展性要求很高的系统框架上,普通程序不建议使用。
- 使用反射会模糊程序内部逻辑;程序员希望在源代码中看到程序的逻辑,反射却绕过了源代码的技术,因而会带来维护的问题,反射代码比相应的直接代码更复杂。
应用场景
- 逆向代码 ,例如反编译
- 与注解相结合的框架 例如Retrofit
- 单纯的反射机制应用框架 例如EventBus 2.x
- 动态生成类框架 例如Gson
总结
Java的反射机制在平时的业务开发过程中很少使用到,但是在一些基础框架的搭建上应用非常广泛,反射的机制便是操控这些字段、方法、构造函数。