Java反射机制的使用

参考博客:https://www.cnblogs.com/lzfsuifeng/p/9590705.html

博主写的很详细,这里截取部分经常用到的记录下:

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

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

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

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

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

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

生成动态代理;

class对象的获取:

//第一种方式 通过对象getClass方法
Person person = new Person();
Class<?> class1 = person.getClass();

//第二种方式 通过类的class属性
class1 = Person.class;

//第三种方式 通过Class类的静态方法——forName()来实现,此时需要写类的全路径
class1 = Class.forName("com.whoislcj.reflectdemo.Person");

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

Field[] allFields = class1.getDeclaredFields();//获取class对象的所有属性
Field[] publicFields = class1.getFields();//获取class对象的public属性


Field ageField = class1.getDeclaredField("age");//获取class指定属性
Field desField = class1.getField("des");//获取class指定的public属性


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


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

class对象动态生成

Object obj = class1.newInstance();

通过反射机制获取注解信息

  //首先需要获得与该方法对应的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();//获取方法的返回类型

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值