0
  • 聊天消息
  • 系统消息
  • 评论与回复
登录后你可以
  • 下载海量资料
  • 学习在线课程
  • 观看技术视频
  • 写文章/发帖/加入社区
会员中心
创作中心

完善资料让更多小伙伴认识你,还能领取20积分哦,立即完善>

3天内不再提示

Java反射机制到底是什么?有什么作用

Wildesbeast 来源:今日头条 作者:程序猿的内心独白 2020-02-15 14:07 次阅读
加入交流群
微信小助手二维码

扫码添加小助手

加入工程师交流群

什么是Java反射机制?

Java反射机制是 Java 语言的一个重要特性,它在服务器程序和中间件程序中得到了广泛运用。在服务器端,往往需要根据客户的请求,动态调用某一个对象的特定方法。此外,在 ORM 中间件的实现中,运用 Java 反射机制可以读取任意一个 JavaBean 的所有属性,或者给这些属性赋值

通过反射机制,可以在运行的时候访问到对象的属性、方法、构造方法等等

哪些地方用到反射机制?

其实我们都用过反射机制,只是并不知道它是反射机制而已。比如我们使用JDBC连接数据库的时候(Class.forName() 这个相信大家都用过),只是当时并没有在意那么多(心里想能用就行,管它呢),使用到反射机制的框架有(Spring、SpringMVC、Mybatis、Hibernate、Structs)

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

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

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

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

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

生成动态代理

如何实现反射机制?

先来个实体类 Student

/**

* @author Woo_home

* @create by 2019/12/10

*/

public class Student {

private int id;

private String name;

public Student(){}

public int getId() {

return id;

}

public void setId(int id) {

this.id = id;

}

public String getName() {

return name;

}

public void setName(String name) {

this.name = name;

}

@Override

public String toString() {

return "Student{" +

"id=" + id +

", name='" + name + ''' +

'}';

}

}

反射的三种实现方式

一、通过对象的getClass()方法

getClass()方法是Object类的方法,因为所有类都继承自Object类,所以可以直接使用getClass()方法

public class ReflectDemo {

public static void main(String[] args) {

Student student = new Student();

Class studentClass = student.getClass();

System.out.println(studentClass);

}

}

二、通过类的.class属性

直接获取一个类的class

public class ReflectDemo {

public static void main(String[] args) {

Class studentClass = Student.class;

System.out.println(studentClass);

}

}

三、通过Class类的forName()方法(常用)

Class.forName() 是一个静态方法

public class ReflectDemo {

public static void main(String[] args) {

// 使用 try、catch 处理异常

try {

Class studentClass = Class.forName("com.example.app.demo.Student");

System.out.println(studentClass);

}catch (ClassNotFoundException e){

e.printStackTrace();

}

}

}

public class ReflectDemo {

// 使用 throws 处理异常

public static void main(String[] args) throws ClassNotFoundException{

Class studentClass = Class.forName("com.example.app.demo.Student");

System.out.println(studentClass);

}

}

三种方法打印的结果都是一样的,如下图所示

注意: 这里的Class.forName()方法需要使用try、catch语句括住或者在方法或类中抛出ClassNotFoundException 异常,不然会报错

有些人就问了,为什么需要使用try、catch语句括住呢,来看下forName方法源码:

可以看到forName需要抛出一个 ClassNotFoundException 异常,自然而然地你使用forName()方法也自然要抛出 / 处理日常了

@CallerSensitive

public static Class forName(String className)

throws ClassNotFoundException {

Class caller = Reflection.getCallerClass();

return forName0(className, true, ClassLoader.getClassLoader(caller), caller);

}

判断一个类是否为某个类的实例

1、instanceof

public class ReflectDemo {

public static void main(String[] args) {

HashMap map = new HashMap<>();

if (map instanceof Map){

System.out.println("HashMap is Map instance");

}

}

}

输出:HashMap is Map instance

2、isInstance

public class ReflectDemo {

public static void main(String[] args) {

HashMap map = new HashMap<>();

if (Map.class.isInstance(map)){

System.out.println("HashMap is Map Instance");

}

}

}

输出:HashMap is Map Instance

利用反射创建对象实例

1、通过Class对象的 newInstance() 方法

public class ReflectDemo {

public static void main(String[] args) throws IllegalAccessException, InstantiationException {

// 这里的Student是使用上面一开始的Student类

Class studentClass = Student.class;

// 使用newInstance创建实例

Student student = (Student)studentClass.newInstance();

student.setId(1);

student.setName("John");

System.out.println(student);

}

}

输出:John

2、通过Constructor对象的 getConstructor() 方法

public class ReflectDemo {

public static void main(String[] args) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException {

Class classes = List.class;

Constructor constructor = classes.getConstructor(List.class);

List result = (List) constructor.newInstance("John");

System.out.println(result);

}

}

输出:John

Field

根据字段名获取字段(只能获取public的)

public class ReflectDemo {

public static void main(String[] args) throws NoSuchFieldException {

Class classes = Student.class;

Field id = classes.getField("id");

Field name = classes.getField("name");

System.out.println(id);

System.out.println(name);

}

}

class Student{

public int id;

public String name;

}

输出:

以下为输出结果

public int com.example.app.demo.Student.id

public java.lang.String com.example.app.demo.Student.name

如果获取的字段是被private修饰的,那么将会抛出 NoSuchFieldException 异常

以下为输出结果

Exception in thread “main” java.lang.NoSuchFieldException: id

at java.lang.Class.getField(Class.java:1703)

at com.example.app.demo.ReflectDemo.main(ReflectDemo.java:12)

为什么会这样呢?我们朝着这个问题看下源码是怎么实现的

getField(String name)

根据名称获取公有的(public)类成员

@CallerSensitive

public Field getField(String name)

throws NoSuchFieldException, SecurityException {

checkMemberAccess(Member.PUBLIC, Reflection.getCallerClass(), true);

// 可以看到在getField传入的name实际是调用getField0来实现的

Field field = getField0(name);

if (field == null) {

throw new NoSuchFieldException(name);

}

return field;

}

getField0(String name)

而getField0主要判断依据是searchFields,searchFields根据privateGetDeclaredFields判断

private Field getField0(String name) throws NoSuchFieldException {

Field res;

// Search declared public fields

if ((res = searchFields(privateGetDeclaredFields(true), name)) != null) {

return res;

}

// 省略部分代码...

return null;

}

privateGetDeclaredFields(boolean publicOnly)

可以看到当privateGetDeclaredFields传入的值是true的时候表示使用的是 declaredPublicFields ,也就是说是public声明的字段,当传入的值为false的时候使用的是 declaredFields(所有声明字段)

private Field[] privateGetDeclaredFields(boolean publicOnly) {

checkInitted();

Field[] res;

ReflectionData rd = reflectionData();

if (rd != null) {

// 判断输入的布尔值是true还是false

res = publicOnly ? rd.declaredPublicFields : rd.declaredFields;

if (res != null) return res;

}

// 省略部分代码...

return res;

}

getFields(String name)

获取所有 public 修饰的字段

public class ReflectDemo {

public static void main(String[] args) throws NoSuchFieldException {

Class classes = Student.class;

Field[] allField = classes.getFields();

for (Field field : allField) {

System.out.println(field);

}

}

}

class Student{

private int id;

public String name;

}

输出:

以下为输出结果

public java.lang.String com.example.app.demo.Student.name

可以看到我们的Student类中声明了一个private修饰的id和一个public修饰的name,根据输出结果可以知道getFields()方法只能获取public修饰的字段

看下实现源码:

在getFields中返回了一个copyFields方法,该方法中调用了 privateGetPublicFields 方法

@CallerSensitive

public Field[] getFields() throws SecurityException {

checkMemberAccess(Member.PUBLIC, Reflection.getCallerClass(), true);

return copyFields(privateGetPublicFields(null));

}

来看下privateGetPublicFields方法可以知道在该方法中调用了 privateGetDeclaredFields(true) 这个方法,关于这个方法上面已经讲述过

private Field[] privateGetPublicFields(Set> traversedInterfaces) {

// Local fields

Field[] tmp = privateGetDeclaredFields(true);

addAll(fields, tmp);

// 省略部分代码...

return res;

}

getDeclaredField(String name)

根据名称获取已声明的类成员。但不能得到其父类的类成员

public class ReflectDemo {

public static void main(String[] args) throws NoSuchFieldException {

Class classes = Student.class;

Field allField = classes.getDeclaredField("name");

System.out.println(allField);

}

}

class Student{

private int id;

private String name;

}

Class Student{

public int id;

public String name;

}

输出:可以看到getDeclaredField()方法即可以获取public类型的字段也能获取private类型的字段

以下为输出结果:

private java.lang.String com.example.app.demo.Student.name

public java.lang.String com.example.app.demo.Student.name

来看下源码的原理

@CallerSensitive

public Field getDeclaredField(String name)

throws NoSuchFieldException, SecurityException {

checkMemberAccess(Member.DECLARED, Reflection.getCallerClass(), true);

Field field = searchFields(privateGetDeclaredFields(false), name);

if (field == null) {

throw new NoSuchFieldException(name);

}

return field;

}

可以看到 getDeclaredField() 方法调用的也是 privateGetDeclaredFields 方法,上面已经讲述过

getDeclaredFields()

获取所有已声明的类成员变量

public class ReflectDemo {

public static void main(String[] args) {

Class classes = Student.class;

Field[] allField = classes.getDeclaredFields();

for (Field field : allField) {

System.out.println(field);

}

}

}

class Student{

public int id;

public String name;

}

输出:

以下为输出结果:

public int com.example.app.demo.Student.id

public java.lang.String com.example.app.demo.Student.name

而且 getDeclaredFields 还可以获取private修饰的字段

public class ReflectDemo {

public static void main(String[] args) {

Class classes = Student.class;

Field[] allField = classes.getDeclaredFields();

for (Field field : allField) {

System.out.println(field);

}

}

}

class Student{

private int id;

private String name;

}

输出:

以下为输出结果:

private int com.example.app.demo.Student.id

private java.lang.String com.example.app.demo.Student.name

来看下源码 getDeclaredFields() 方法的源码

可以看到 getDeclaredFields() 方法中也是调用 privateGetDeclaredFields 方法的,并且这里的 privateGetDeclaredFields传入的值是 false ,也就是获取所有已声明的字段

@CallerSensitive

public Field[] getDeclaredFields() throws SecurityException {

checkMemberAccess(Member.DECLARED, Reflection.getCallerClass(), true);

return copyFields(privateGetDeclaredFields(false));

}

Method

getMethod(String name)

返回类或接口的特定方法。其中第一个参数为方法名称,后面的参数为方法参数对应 Class 的对象的方法名

public class ReflectDemo {

public static void main(String[] args) throws NoSuchMethodException {

// 传入CaseMethod的方法名

Method methods = CaseMethod.class.getMethod("caseOfMethod");

System.out.println(methods);

}

}

class CaseMethod{

public void caseOfMethod(){

System.out.println("case");

}

}

输出:

以下为输出结果:

public void com.example.app.demo.CaseMethod.caseOfMethod()

getMethods()

获取类或接口的所有 public 方法,包括其父类的 public 方法

public class ReflectDemo {

public static void main(String[] args) throws NoSuchMethodException {

// 获取所有方法,使用Method数组接收

Method[] methods = CaseMethod.class.getMethods();

for (Method method : methods) {

System.out.println(method);

}

}

}

class CaseMethod{

public void caseOfMethod(){

System.out.println("case");

}

}

输出:

可以看到输出结果中第一个就是我们自定义的CaseMethod中的方法,其余的都是Object类的方法

以下为输出结果:

public void com.example.app.demo.CaseMethod.caseOfMethod()

public final void java.lang.Object.wait() throws java.lang.InterruptedException

public final void java.lang.Object.wait(long,int) throws java.lang.InterruptedException

public final native void java.lang.Object.wait(long) throws java.lang.InterruptedException

public boolean java.lang.Object.equals(java.lang.Object)

public java.lang.String java.lang.Object.toString()

public native int java.lang.Object.hashCode()

public final native java.lang.Class java.lang.Object.getClass()

public final native void java.lang.Object.notify()

public final native void java.lang.Object.notifyAll()

getDeclaredMethod(String name, Class… parameterTypes)

获取类或接口的特定声明方法。其中第一个参数为方法名称,后面的参数为方法参数对应 Class 的对象

public class ReflectDemo {

public static void main(String[] args) throws NoSuchMethodException {

Method methods = CaseMethod.class.getDeclaredMethod("caseOfMethod",null);

System.out.println(methods);

}

}

class CaseMethod{

public void caseOfMethod(){

System.out.println("case");

}

private void caseOf(){

System.out.println("case1");

}

}

getDeclaredMethods()

获取类或接口声明的所有方法,包括 public、protected、默认(包)访问和 private 方法,但不包括继承的方法

public class ReflectDemo {

public static void main(String[] args) {

Method[] methods = CaseMethod.class.getDeclaredMethods();

for (Method method : methods) {

System.out.println(method);

}

}

}

class CaseMethod{

public void caseOfMethod(){

System.out.println("case");

}

private void caseOf(){

System.out.println("case1");

}

}

输出:

以下为输出结果:

public void com.example.app.demo.CaseMethod.caseOfMethod()

private void com.example.app.demo.CaseMethod.caseOf()

使用invoke方法

当获取一个对象之后就可以使用invoke方法,invoke方法示例如下:

public class ReflectDemo {

public static void main(String[] args) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException {

Method methods = CaseMethod.class.getMethod("caseOfMethod");

CaseMethod caseMethod = new CaseMethod();

methods.invoke(caseMethod);

}

}

class CaseMethod{

public void caseOfMethod(){

System.out.println("case");

}

private void caseOf(){

System.out.println("case1");

}

}

输出:case

那么invoke是如何实现的呢?来看下源码

boolean override;

@CallerSensitive

public Object invoke(Object obj, Object... args)

throws IllegalAccessException, IllegalArgumentException,

InvocationTargetException

{

// 判断override是否为true

if (!override) {

// 判断modifiers(方法的修饰符)是否为public

if (!Reflection.quickCheckMemberAccess(clazz, modifiers)) {

// 通过方法的修饰符(protected、private、)或声明类(如子类可以访问父类的protected方法)与caller之间的关系

Class caller = Reflection.getCallerClass();

// 判断caller是否有权限方法该方法

checkAccess(caller, clazz, obj, modifiers);

}

}

MethodAccessor ma = methodAccessor; // read volatile

if (ma == null) {

ma = acquireMethodAccessor();

}

return ma.invoke(obj, args);

}

注意: invoke方法如果提供了错误的参数,会抛出一个异常,所以要提供一个异常处理器。建议在有必要的时候才使用invoke方法,有如下原因:

1、invoke方法的参数和返回值必须是Object类型,意味着必须进行多次类型转换

2、通过反射调用方法比直接调用方法要明显慢一些

Constructor

getConstructor(Class… parameterTypes)

获取类的特定 public 构造方法。参数为方法参数对应 Class 的对象

public class ReflectDemo {

public static void main(String[] args) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException {

Constructor constructor = CaseMethod.class.getConstructor(int.class, String.class);

System.out.println(constructor);

}

}

class CaseMethod{

private int id;

private String name;

private int cap;

public CaseMethod(int id,String name){

this.id = id;

this.name = name;

}

public CaseMethod(int cap){

}

}

输出:

以下为输出结果:

public com.example.app.demo.CaseMethod(int,java.lang.String)

getConstructors()

获取类的所有 public 构造方法

public class ReflectDemo {

public static void main(String[] args) {

Constructor[] constructors = CaseMethod.class.getConstructors();

for (Constructor constructor : constructors) {

System.out.println(constructor);

}

}

}

class CaseMethod{

private int id;

private String name;

private int cap;

public CaseMethod(int id,String name){

this.id = id;

this.name = name;

}

public CaseMethod(int cap){

}

}

输出:

以下为输出结果:

public com.example.app.demo.CaseMethod(int,java.lang.String)

public com.example.app.demo.CaseMethod(int)

getDeclaredConstructor(Class… parameterTypes)

public class ReflectDemo {

public static void main(String[] args) throws NoSuchMethodException {

// 注意:由于private修饰的CaseMethod构造函数没有参数,所以getDeclaredConstructor()可以为空

// 默认的getDeclaredConstructor(Class... parameterTypes)方法是要传参数类型的

Constructor constructor = CaseMethod.class.getDeclaredConstructor();

Constructor declaredConstructor = CaseMethod.class.getDeclaredConstructor(int.class, String.class);

System.out.println(constructor);

System.out.println(declaredConstructor);

}

}

class CaseMethod{

private int id;

private String name;

private int cap;

private CaseMethod(){

}

public CaseMethod(int id,String name){

this.id = id;

this.name = name;

}

}

输出:

以下为输出结果:

private com.example.app.demo.CaseMethod()

public com.example.app.demo.CaseMethod(int,java.lang.String)

getDeclaredConstructors()

获取类的所有构造方法

public class ReflectDemo {

public static void main(String[] args) throws NoSuchMethodException {

Constructor[] constructors = CaseMethod.class.getDeclaredConstructors();

for (Constructor constructor : constructors) {

System.out.println(constructor);

}

}

}

class CaseMethod{

private int id;

private String name;

private int cap;

private CaseMethod(){

}

public CaseMethod(int id,String name){

this.id = id;

this.name = name;

}

}

输出:

以下为输出结果:

private com.example.app.demo.CaseMethod()

public com.example.app.demo.CaseMethod(int,java.lang.String)

使用newInstance创建实例

public class ReflectDemo {

public static void main(String[] args) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException {

Constructor constructor = CaseMethod.class.getConstructor(String.class);

CaseMethod caseMethod = constructor.newInstance("Lisa");

System.out.println(caseMethod);

}

}

class CaseMethod{

private String name;

public CaseMethod(String name){

this.name = name;

}

@Override

public String toString() {

return "CaseMethod{" +

"name='" + name + ''' +

'}';

}

}

输出:

CaseMethod{name=‘Lisa’}

总结

Java获得Class对象的引用的方法中,Class.forName() 方法会自动初始化Class对象,而 .class 方法不会,.class 的初始化被延迟到静态方法或非常数静态域的首次引用

声明:本文内容及配图由入驻作者撰写或者入驻合作网站授权转载。文章观点仅代表作者本人,不代表电子发烧友网立场。文章及其配图仅供工程师学习之用,如有内容侵权或者其他违规问题,请联系本站处理。 举报投诉
  • 服务器
    +关注

    关注

    13

    文章

    10094

    浏览量

    90882
  • JAVA
    +关注

    关注

    20

    文章

    2997

    浏览量

    115682
  • 数据库
    +关注

    关注

    7

    文章

    3993

    浏览量

    67736
收藏 人收藏
加入交流群
微信小助手二维码

扫码添加小助手

加入工程师交流群

    评论

    相关推荐
    热点推荐

    请问Keil中的map文件到底是什么意思?

    Keil中的map文件到底是什么意思?里面是如何进行相关执行操作的
    发表于 11-25 06:59

    IEC 到底是什么?为什么它能影响全球?

    IEC 到底是什么?为什么它能影响全球?
    的头像 发表于 09-04 17:07 2459次阅读

    晶振的 “负载电容” 到底是什么

    负载电容,到底是什么? 负载电容,简单来说,是指晶振的两条引线连接IC块内部及外部所有有效电容之和,我们可以将其看作晶振片在电路中串接的电容。从更专业的角度讲,它是为了使晶振能够在其标称频率下稳定
    的头像 发表于 07-25 16:26 670次阅读

    请问编译纯rtos到底是选择Linux+rtos的sdk编译only rtos还是直接使用rtos sdk?

    编译纯rtos到底是选择Linux+rtos的sdk编译only rtos还是直接使用rtos sdk?
    发表于 07-11 07:22

    智能盒子到底是什么东西?昇腾310深度测评:为何能成为行业新宠?

    让人摸不着头脑的“智能盒子”。各位搞技术、搞工程的朋友,咱们在工作中是不是经常听到“智能盒子”这个说法?每次听到这个词,我猜很多人心里都在犯嘀咕:这东西到底是个啥玩意儿?难道就是个装了点智能软件的普通盒子?它到底有啥用?能给咱们的工作带来啥方便?
    的头像 发表于 04-27 10:46 1498次阅读
    智能盒子<b class='flag-5'>到底是</b>什么东西?昇腾310深度测评:为何能成为行业新宠?

    一文给你讲透!DA板卡到底是什么?它和主板又有哪些不同?

    大家好,我是老王,在电子行业干了十几年,今天我就用“大白话”给大家讲讲DA板卡到底是啥,它和咱们常说的“主板”啥区别。文章里会穿插一些表格和实际案例,保证你读完不仅能懂,还能跟朋友吹牛!
    的头像 发表于 04-24 16:48 1664次阅读
    一文给你讲透!DA板卡<b class='flag-5'>到底是</b>什么?它和主板又有哪些不同?

    Java的SPI机制详解

    作者:京东物流 杨苇苇 1.SPI简介 SPI(Service Provicer Interface)是Java语言提供的一种接口发现机制,用来实现接口和接口实现的解耦。简单来说,就是系统只需要定义
    的头像 发表于 03-05 11:35 1111次阅读
    <b class='flag-5'>Java</b>的SPI<b class='flag-5'>机制</b>详解

    ADS1298 RDATAC Opcode时,START到底是低还是高?

    您好,1298的datasheet看到这有点糊涂了。 1、RDATAC Opcode时,START到底是低还是高? 从时序图上看实线是高、虚线是低,请问实线虚线什么区别? 2、同时在DOUT
    发表于 02-14 07:48

    ADS1298 tdr的值到底是多大,跟采样率等有没有什么关系?

    我想请问一下, 1、tdr的值到底是多大,跟采样率等有没有什么关系。数据手册上只找到建立时间,好像没有这个时间的值,28页那个最小SCLK时钟为110khz是怎么计算的。 2、 tdr到底是
    发表于 02-13 06:11

    ADS1298的操作温度范围到底是多少?

    ADS1298是 0°Cto +70°C;工业级ADS1298I 是 –40°Cto +85°C。 现在不知道ADS1298的操作温度范围到底是多少?
    发表于 02-10 07:19

    ADS1298ECG-FE原理图上看见很多NI的符号, 到底是什么意思呢?

    我们在ADS1298ECG-FE原理图上看见很多NI的符号, 到底是什么意思呢? 具体的值是多少呢? 如下面两个图所示: R1, R2电阻的值是多少? 这个比较重要。 R59 - R66又是多少? 麻烦你们回答一下。 谢谢
    发表于 02-05 08:16

    ADS1278的参考电压的要求到底是怎样的?

    <27MHz为例,Vrefp输入范围为0.5到3.1V 而后文又提到,参考输入电压的范围为AGND-0.4v to AVDD+0.4v 问题1. 这个参考电压的要求到底是怎样的? 问题2.
    发表于 01-23 08:02

    TLC2578芯片中FS与SDI到底有什么作用

    ,还有就是一点不太懂的就是:TLC2578芯片中FS与SDI到底有什么作用。手册看了半天还是不懂!求解!谢谢!
    发表于 01-22 06:51

    ADS7864采样频率到底是由外部时钟决定还是HOLDX信号频率决定?

    ADS7864数据手册上说当采用8M外部时钟的时候,采样频率为500kHz,但是有人说可以通过HOLDX频率来控制采样频率,一个HOLDX下降沿采样一次,HOLDX频率就是采样频率。请问采样频率到底是由外部时钟决定还是HOLDX信号频率决定?
    发表于 01-14 06:47

    LM629 PID参数调节,所谓的高频震荡到底是什么意思?

    为何我的系统一直没有所谓的高频震荡这种现象;只是随着Kd的增加,系统的阻尼开始变大而已。所谓的高频震荡到底是什么意思?
    发表于 01-01 07:30