Java中的反射

1.什么是反射?

反射是框架设计的灵魂。

反射(Reflection)是 Java 的一种特性,它可以让程序在运行时获取自身的信息,并且动态地操作类或对象的属性、方法和构造器等。通过反射功能,可以让我们在不知道具体类名的情况下,依然能够实例化对象,调用方法以及设置属性。简单来说就是在类运行的过程中,把类中的成员抽取为其他类的过程就是反射。

2.为什么使用反射?

反射是为了解决在运行期,在对某个实例一无所知的情况下,去调用其方法或属性。

例如在spring框架中,传入类的路径,spring会自动帮你创建类的对象。

3.获取Class反射类的三种方式

第一种:通过类名.class属性

Class aClass = Student.class;

第二种:通过类路径获取

Class aClass1 = Class.forName("com.ls.test.Student");

第三种:通过对象名获取反射类型

Student student =new Student();
Class aClass2 = student.getClass();

4.Class类中常用的方法

1.根据反射类得到实例对象。   newInstance():

Class<Student> aClass = Student.class;
Student student = aClass.newInstance();

2.得到反射类上的注解对象。 getAnnotation() :

MyAnnotation annotation = aClass.getAnnotation(MyAnnotation.class);
System.out.println(annotation.value());

5.获取Method方法类对象

1.getDeclaredMethods():得到本类中所有的方法。

Method[] declaredMethods = aClass.getDeclaredMethods();

2.getDeclaredMethod():获取本类中指定的方法对象。

Method study = aClass.getDeclaredMethod("study", null);

3.getMethods():获取本类以及父类中public修饰的方法。

Method[] methods = aClass.getMethods();

4.getMethod(): 获取本类以及父类中指定的public方法对象。

Method study1 = aClass.getMethod("study");

6.Method类对象中常用的方法

1.invoke(Object对象,参数值):执行该方法,返回该方法返回的结果。

Class<?> aClass = Class.forName("com.ls.test.People");
Object o = aClass.newInstance();
Method method = aClass.getMethod("print", Integer.class);
Object result = method.invoke(o, 20);

2.setAccessible()设置允许访问私有成员方法或变量

Method aDo = aClass.getDeclaredMethod("Do", String.class);
Object love = aDo.invoke(o, "爱");

私有方法不能被反射调用,要用强力反射。
Method method1 = aClass.getDeclaredMethod("Do", String.class);
method1.setAccessible(true);
Object result1 = method1.invoke(o, "爱");

7.获取Field属性对象的方式

8.Field类中的常用的方法

1.set(Object对象,值):为属性赋值

2.getName():获取属性名

3.getAnnotation():获取属性上的注解对象

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值