一 什么是反射
无法通过new 关键字来获取对象并调用方法,通过JDK提供的反射API来进行反射调用,反射是在运行时才知道要操作的类是什么,并且可以在运行时获取类的完整构造,获取相关方法。
反射原理:每一个类 在JVM中都是Class类的对象,且Class对象唯一, 每个对象在编译成Class对象时,会在.class文件末尾保留类的源数据信息,包括路径 类名 属性 方法 继承关系
二 反射使用
1 反射获取对象Class

参数是完整报名+类名,其内部实现如下:

第二个参数boolean值如果为true,则会执行对象的初始化过程,static代码块会被执行
2 获取对象

3 获取方法并调用:
获取构造方法:

构造方法调用:

普通方法获取:
//获取所有非privite方法,包括从父类继承来的方法
Method[] methods1 = cClass.getMethods();
//获取所有方法,包括privite方法,但仅限于该类
Method[] methods1 = cClass.getDeclaredMethods();
//获取特定方法,第一个参数是方法名,第二个参数是方法的参数类型
cClass.getDeclaredMethod("setNumber",Integer.TYPE);
方法调用:


4 获取属性


三 总结
反射是在运行时获取,先天比new 要慢。
网友评论