五分钟,带你重温Java反射原理及应用!(超详细)

反射

反射经常听到这个词,但是总是不理解这个意思。今天便来理解一下反射这个概念,为什么说在框架设计中,反射用到的比较多。

  • 反射指程序可以访问、检测和修改它本身状态或行为的一种能力。
  • 官方定义:提供封装程序集、模块和类型的对象
  • 整理后的定义:
  • 封装了程序集的对象
  • 封装了模块的对象
  • 封装了类型的对象

什么是Java反射机制?

JAVA反射机制是在运行状态中,对于任意一个类,都能够知道这个类的所有属性和方法;对于任意一个对象,都能够调用它的任意一个方法;这种动态获取的以及动态调用对象的方法的功能称为Java的反射机制。

反射机制提供了哪些功能?

  • 在运行时判定任意一个对象所属的类

  • 在运行时构造任意一个类的对象;

  • 在运行时判定任意一个类所具有的成员变量和方法;

  • 在运行时调用任意一个对象的方法;

  • 生成动态代理;

Class

Class 与 class 有着本质的区别。小写的 class 是 Java 中的关键字,而大写的 Class 则是类。

public final class Class<T> implements java.io.Serializable,
                              GenericDeclaration,
                              Type,
                              AnnotatedElement {
}

Java反射机制实现

class对象的获取

//第一种方式 通过对象getClass方法
Person person = new Person();
Class<?> class1 = person.getClass();
//第二种方式 通过类的class属性
class1 = Person.class;
try {
    //第三种方式 通过Class类的静态方法——forName()来实现
    class1 = Class.forName("com.whoislcj.reflectdemo.Person");
} catch (ClassNotFoundException e) {
    e.printStackTrace();
}

Class 使用

JAVA反射机制是在运行状态中,对于任意一个类,都能够知道这个类的所有属性和方法;对于任意一个对象,都能够调用它的任意一个方法和属性;这种动态获取的信息以及动态调用对象的方法的功能称为java语言的反射机制。

CLASS 名称获取 对于 name 的获取,Class 类提供了三种方法:

Class.getName();
Class.getSimpleName();
Class.getCanonicalName();

获取class对象的摘要信息

boolean isPrimitive = class1.isPrimitive();//判断是否是基础类型
boolean isArray = class1.isArray();//判断是否是集合类
boolean isAnnotation = class1.isAnnotation();//判断是否是注解类
boolean isInterface = class1.isInterface();//判断是否是接口类
boolean isEnum = class1.isEnum();//判断是否是枚举类
boolean isAnonymousClass = class1.isAnonymousClass();//判断是否是匿名内部类
boolean isAnnotationPresent = class1.isAnnotationPresent(Deprecated.class);//判断是否被某个注解类修饰

String className = class1.getName();//获取class名字 包含包名路径
Package aPackage = class1.getPackage();//获取class的包信息
String simpleName = class1.getSimpleName();//获取class类名
int modifiers = class1.getModifiers();//获取class访问权限

Class<?>[] declaredClasses = class1.getDeclaredClasses();//内部类
Class<?> declaringClass = class1.getDeclaringClass();//外部类

获取class对象的属性、方法、构造函数等

Field[] allFields = class1.getDeclaredFields();//获取class对象的所有属性
Field[] publicFields = class1.getFields();//获取class对象的public属性
try {
    Field ageField = class1.getDeclaredField("age");//获取class指定属性
    Field desField = class1.getField("des");//获取class指定的public属性
} catch (NoSuchFieldException e) {
    e.printStackTrace();
}

Method[] methods = class1.getDeclaredMethods();//获取class对象的所有声明方法
Method[] allMethods = class1.getMethods();//获取class对象的所有方法 包括父类的方法

Class parentClass = class1.getSuperclass();//获取class对象的父类
Class<?>[] interfaceClasses = class1.getInterfaces();//获取class对象的所有接口

Constructor<?>[] allConstructors = class1.getDeclaredConstructors();//获取class对象的所有声明构造函数
Constructor<?>[] publicConstructors = class1.getConstructors();//获取class对象public构造函数
try {
    Constructor<?> constructor = class1.getDeclaredConstructor(new Class[]{String.class});//获取指定声明构造函数
    Constructor publicConstructor = class1.getConstructor(new Class[]{});//获取指定声明的public构造函数
} catch (NoSuchMethodException e) {
    e.printStackTrace();
}

Annotation[] annotations = class1.getAnnotations();//获取class对象的所有注解
Annotation annotation = class1.getAnnotation(Deprecated.class);//获取class对象指定注解

Type genericSuperclass = class1.getGenericSuperclass();//获取class对象的直接超类的 Type
Type[] interfaceTypes = class1.getGenericInterfaces();//获取class对象的所有接口的type集合

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的反射机制在平时的业务开发过程中很少使用到,但是在一些基础框架的搭建上应用非常广泛,反射的机制便是操控这些字段、方法、构造函数。

  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值