大多数人不知道的Java知识 - Java内省机制

简介: 大多数人不知道的Java知识 - Java内省机制

@TOC


# Java 内省机制 在计算机科学中,内省是指计算机程序在运行时(Runtime)检查对象(Object)类型的一种能力,也叫运行时类型检查。 内省和反射是不同概念。相对于内省,反射更进一步,反射是指计算机程序在运行时(Runtime)可以访问、检测和修改它本身状态或行为的一种能力。内省底层是利用了反射原理。 Java内省(Introspector)是Java语言对Bean类属性、方法,事件的一种缺省处理方法。例如类Person中有属性name,那我们可以通过getName,setName来得到其值或者设置新的值。通过getName/setName来访问name属性,这就是默认的规则。Java中提供了一套API用来访问某个属性的getter/setter方法,通过这些API可以使你不需要了解这个规则(但你最好还是要搞清楚),这些API存放于包java.beans中。 一般的做法是通过类Introspector来获取某个对象的BeanInfo信息,然后通过BeanInfo来获取属性的描述器PropertyDescriptor,通过这个属性描述器就可以获取某个属性对应的getter/setter方法,最后就可以通过反射机制来调用这些方法了。
# Introspector **官方介绍** The Introspector class provides a standard way for tools to learn about the properties, events, and methods supported by a target Java Bean. For each of those three kinds of information, the Introspector will separately analyze the bean's class and superclasses looking for either explicit or implicit information and use that information to build a BeanInfo object that comprehensively describes the target bean. `java.beans.Introspector`,即`内省`。它提供了一套标准的访问Java Bean的`属性`,`事件`以及`方法`的处理方法。 对于Java Bean的这3种信息,Introspector会分析Java Bean以及它的父类的显示和隐式的信息,然后构建一个全面描述此Java Bean的`BeanInfo`对象。 在Java中,JavaBean是一种特殊的类,主要用于传递数据信息,这种类中的方法主要用于访问私有的属性,且方法名符合某种命名规则。例如DTO,VO等,我们在业务或者模块之间传递信息,可以将信息封装到JavaBean中。 既然封装到JavaBean中,那就会有设置(setter)和读取(getter)JavaBean中私有属性等操作。Introspector可以帮我们做到这件事,不过要注意,`JavaBean中的getter和setter等方法要遵循某种规范。(驼峰规则)` ```java package com.nobody; /** * @Description JavaBean类 * @Author Mr.nobody * @Date 2021/1/24 * @Version 1.0 */ public class Person { private String id; private String name; private int age; public Person(String id, String name, int age) { this.id = id; this.name = name; this.age = age; } public String getId() { return id; } public void setId(String id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } } ``` ```java package com.nobody; import java.beans.*; /** * @Description * @Author Mr.nobody * @Date 2021/3/23 * @Version 1.0.0 */ public class Demo { public static void main(String[] args) throws IntrospectionException { // 不内省父类的信息,第二个参数stopClass代表从stopClass开始往上的父类不再内省 BeanInfo beanInfo = Introspector.getBeanInfo(Person.class, Object.class); // 会内省起所有父类的信息 BeanInfo includeParentBeanInfo = Introspector.getBeanInfo(Person.class); } } ```
# BeanInfo **官方介绍** Use the BeanInfo interface to create a BeanInfo class and provide explicit information about the methods, properties, events, and other features of your beans. `java.beans.BeanInfo`是一个接口,它有几个默认的实现类,我们一般默认生成的BeanInfo对象其实是GenericBeanInfo类的实例。简而言之,BeanInfo对象能提供关于JavaBean的方法,属性,事件以及其他特征的明确信息。 其主要方法如下: - getPropertyDescriptors():获得所有属性描述器。 - getBeanDescriptor():获得对象描述器。 - getMethodDescriptors():获得所有方法描述器。 - getEventSetDescriptors():获得所有事件描述器。 ```java package com.nobody; import java.beans.*; /** * @Description * @Author Mr.nobody * @Date 2021/3/23 * @Version 1.0.0 */ public class Demo { public static void main(String[] args) throws IntrospectionException { // 不内省父类的信息,第二个参数stopClass代表从stopClass开始往上的父类不再内省 BeanInfo beanInfo = Introspector.getBeanInfo(Person.class, Object.class); BeanDescriptor beanDescriptor = beanInfo.getBeanDescriptor(); PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors(); MethodDescriptor[] methodDescriptors = beanInfo.getMethodDescriptors(); EventSetDescriptor[] eventSetDescriptors = beanInfo.getEventSetDescriptors(); } } ```
# BeanDescriptor **官方介绍** A BeanDescriptor provides global information about a "bean", including its Java class, its displayName, etc. This is one of the kinds of descriptor returned by a BeanInfo object, which also returns descriptors for properties, method, and events. `java.beans.BeanDescriptor`,即`对象描述器`。它提供了一个JavaBean的全局信息,例如JavaBean的类型,类名等信息。 我们一般是从BeanInfo对象获取BeanDescriptor对象,不过也可以直接通过new BeanDescriptor(Class<?> beanClass)构造函数获取。 ```java package com.nobody; import java.beans.*; /** * @Description * @Author Mr.nobody * @Date 2021/3/23 * @Version 1.0.0 */ public class Demo { public static void main(String[] args) throws IntrospectionException { // 不内省父类的信息,第二个参数stopClass代表从stopClass开始往上的父类不再内省 BeanInfo beanInfo = Introspector.getBeanInfo(Person.class, Object.class); // 从BeanInfo对象获取BeanDescriptor对象 BeanDescriptor beanDescriptor = beanInfo.getBeanDescriptor(); // 通过new BeanDescriptor(Class<?> beanClass)构造函数获取BeanDescriptor对象 // BeanDescriptor beanDescriptor = new BeanDescriptor(Person.class); Class<?> beanClass = beanDescriptor.getBeanClass(); Class<?> customizerClass = beanDescriptor.getCustomizerClass(); String displayName = beanDescriptor.getDisplayName(); String name = beanDescriptor.getName(); System.out.println("beanClass:" + beanClass); System.out.println("customizerClass:" + customizerClass); System.out.println("displayName:" + displayName); System.out.println("name:" + name); PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors(); MethodDescriptor[] methodDescriptors = beanInfo.getMethodDescriptors(); EventSetDescriptor[] eventSetDescriptors = beanInfo.getEventSetDescriptors(); } } ``` 输出结果如下: ```bash beanClass:class com.nobody.Person customizerClass:null displayName:Person name:Person ```
# PropertyDescriptor **官方介绍** A PropertyDescriptor describes one property that a Java Bean exports via a pair of accessor methods. `java.beans.PropertyDescriptor`,即`属性描述器`。描述了Java Bean的一个属性,通过一对读取方法。即PropertyDescriptor里面封装了JavaBean的其中一个属性的相关信息(例如属性名,属性类型,get和set等方法)。其主要方法如下: - getName():获得属性名。 - getPropertyType():获得属性类型。 - getReadMethod():获得用于读取属性值的方法。 - getWriteMethod():获得用于写入属性值的方法。 - setReadMethod(Method readMethod):设置用于读取属性值的方法。 - setWriteMethod(Method writeMethod):设置用于写入属性值的方法。 ```java package com.nobody; import java.beans.*; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.UUID; /** * @Description * @Author Mr.nobody * @Date 2021/3/23 * @Version 1.0.0 */ public class Demo { public static void main(String[] args) throws IntrospectionException, InvocationTargetException, IllegalAccessException { // 不内省父类的信息,第二个参数stopClass代表从stopClass开始往上的父类不再内省 BeanInfo beanInfo = Introspector.getBeanInfo(Person.class, Object.class); Person person = new Person(UUID.randomUUID().toString(), "Mr_nobody", 18); PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors(); for (PropertyDescriptor propertyDescriptor : propertyDescriptors) { Class<?> propertyType = propertyDescriptor.getPropertyType(); String propertyName = propertyDescriptor.getName(); Method readMethod = propertyDescriptor.getReadMethod(); Method writeMethod = propertyDescriptor.getWriteMethod(); System.out.println("属性名:" + propertyName); System.out.println("属性类型:" + propertyType); System.out.println("写方法名:" + writeMethod.getName()); System.out.println("读方法名:" + readMethod.getName()); if ("age".equals(propertyName)) { writeMethod.invoke(person, 20); } System.out.println("属性值:" + readMethod.invoke(person)); System.out.println("------------------------------------------"); } } } ``` 输出结果: ```bash 属性名:age 属性类型:int 写方法名:setAge 读方法名:getAge 属性值:20 ------------------------------------------ 属性名:id 属性类型:class java.lang.String 写方法名:setId 读方法名:getId 属性值:a6ccda55-c895-438e-893f-7fa448aba35a ------------------------------------------ 属性名:name 属性类型:class java.lang.String 写方法名:setName 读方法名:getName 属性值:Mr_nobody ------------------------------------------ ``` 当然,除了从BeanInfo对象获取PropertyDescriptor对象,也可以直接new的方式获取。 ```java PropertyDescriptor namePropertyDescriptor = new PropertyDescriptor("name", Person.class); ```
# MethodDescriptor java.beans.MethodDescriptor,即方法描述器,通过它可以获取到类相关的方法,如下所示: ```java package com.nobody; import java.beans.*; import java.lang.reflect.Method; import java.lang.reflect.Type; /** * @Description * @Author Mr.nobody * @Date 2021/3/23 * @Version 1.0.0 */ public class Demo { public static void main(String[] args) throws IntrospectionException { // 不内省父类的信息,第二个参数stopClass代表从stopClass开始往上的父类不再内省 BeanInfo beanInfo = Introspector.getBeanInfo(Person.class, Object.class); MethodDescriptor[] methodDescriptors = beanInfo.getMethodDescriptors(); for (MethodDescriptor methodDescriptor : methodDescriptors) { Method method = methodDescriptor.getMethod(); System.out.println(method); System.out.println("方法名:" + method.getName()); Type[] genericParameterTypes = method.getGenericParameterTypes(); if (genericParameterTypes != null) { for (Type genericParameterType : genericParameterTypes) { System.out.println("方法参数类型:" + genericParameterType.getTypeName()); } } Class<?> returnType = method.getReturnType(); System.out.println("方法返回类型:" + returnType.getTypeName()); System.out.println("---------------------------"); } } } ``` 输出结果如下: ```bash public java.lang.String com.nobody.Person.getName() 方法名:getName 方法返回类型:java.lang.String --------------------------- public void com.nobody.Person.setId(java.lang.String) 方法名:setId 方法参数类型:java.lang.String 方法返回类型:void --------------------------- public void com.nobody.Person.setAge(int) 方法名:setAge 方法参数类型:int 方法返回类型:void --------------------------- public void com.nobody.Person.setName(java.lang.String) 方法名:setName 方法参数类型:java.lang.String 方法返回类型:void --------------------------- public int com.nobody.Person.getAge() 方法名:getAge 方法返回类型:int --------------------------- public java.lang.String com.nobody.Person.getId() 方法名:getId 方法返回类型:java.lang.String --------------------------- public java.lang.String com.nobody.Person.toString() 方法名:toString 方法返回类型:java.lang.String --------------------------- ```
# 内省应用 在项目实战中,我们一般使用最多的是 `Introspector`,`BeanInfo`,`PropertyDescriptor`,这三者结合起来使用。 比如,我们通过内省可以实现,JavaBean和Map互转,不同JavaBean对象属性拷贝等功能。 ```java package com.nobody.util; import java.beans.BeanInfo; import java.beans.IntrospectionException; import java.beans.Introspector; import java.beans.PropertyDescriptor; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.*; /** * @Description Bean工具类 * @Author Mr.nobody * @Date 2021/3/23 * @Version 1.0.0 */ public class BeanUtils { public static Map beanToMap(T bean, boolean putIfNull) throws IntrospectionException, InvocationTargetException, IllegalAccessException { if (bean == null) { return new HashMap<>(); } Map returnMap = new HashMap<>(); // 获取bean的BeanInfo对象 BeanInfo beanInfo = Introspector.getBeanInfo(bean.getClass(), Object.class); // 获取属性描述器 PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors(); for (PropertyDescriptor propertyDescriptor : propertyDescriptors) { // 属性名 String propertyName = propertyDescriptor.getName(); // 获取该属性的值 Method readMethod = propertyDescriptor.getReadMethod(); // 属性的值 Object value = readMethod.invoke(bean); if (value == null && !putIfNull) { continue; } returnMap.put(propertyName, value); } return returnMap; } public static List> beansToMaps(List beans, boolean putIfNull) throws IllegalAccessException, IntrospectionException, InvocationTargetException { if (null == beans || beans.size() == 0) { return new ArrayList<>(); } List> result = new ArrayList<>(beans.size() + 1); // 转换每一个bean for (Object bean : beans) { result.add(beanToMap(bean, putIfNull)); } return result; } public static T mapToBean(Map map, Class clz) throws IllegalAccessException, InstantiationException, IntrospectionException, InvocationTargetException { // 生成bean实例 T bean = clz.newInstance(); if (null == map) { return bean; } BeanInfo beanInfo = Introspector.getBeanInfo(clz, Object.class); PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors(); for (PropertyDescriptor propertyDescriptor : propertyDescriptors) { // 属性名 String propertyName = propertyDescriptor.getName(); // 获取属性值 Object value = map.get(propertyName); // 写入属性值 Method writeMethod = propertyDescriptor.getWriteMethod(); writeMethod.invoke(bean, value); } return bean; } public static List mapsToBeans(List> maps, Class clz) throws InvocationTargetException, IntrospectionException, InstantiationException, IllegalAccessException { if (null == maps || maps.size() == 0) { return new ArrayList<>(); } List result = new ArrayList<>(); for (Map map : maps) { result.add(mapToBean(map, clz)); } return result; } public static void copyProperties(T1 origin, T2 dest, boolean setNull, String[] excludeFieldNames) throws IntrospectionException, InvocationTargetException, IllegalAccessException { // 获取源类的BeanInfo对象 BeanInfo originBeanInfo = Introspector.getBeanInfo(origin.getClass(), Object.class); // 获取源类的属性描述器 PropertyDescriptor[] originPropertyDescriptors = originBeanInfo.getPropertyDescriptors(); // 获取目标类的BeanInfo对象 BeanInfo destBeanInfo = Introspector.getBeanInfo(dest.getClass(), Object.class); // 获取目标类的属性描述器 PropertyDescriptor[] destPropertyDescriptors = destBeanInfo.getPropertyDescriptors(); for (PropertyDescriptor propertyDescriptor : destPropertyDescriptors) { String propertyName = propertyDescriptor.getName(); // 是否需要排除的属性 boolean excludeField = false; if (excludeFieldNames != null) { for (String excludeFieldName : excludeFieldNames) { if (Objects.equals(excludeFieldName, propertyName)) { excludeField = true; break; } } } if (excludeField) { continue; } // 遍历源类的所有属性,如果存在此属性则进行拷贝 for (PropertyDescriptor originPropertyDescriptor : originPropertyDescriptors) { String originPropertyName = originPropertyDescriptor.getName(); if (Objects.equals(propertyName, originPropertyName)) { // 读取属性值 Method readMethod = originPropertyDescriptor.getReadMethod(); Object srcValue = readMethod.invoke(origin); if (srcValue != null || setNull) { // 设置属性值 Method writeMethod = propertyDescriptor.getWriteMethod(); writeMethod.invoke(dest, srcValue); } break; } } } } public static void copyProperties(T1 origin, T2 dest) throws IllegalAccessException, IntrospectionException, InvocationTargetException { copyProperties(origin, dest, false, null); } } ``` 以上是我们手写的JavaBean相关的转换工具类,当然市场上已经有很多成熟的工具包了,例如Apache的commons-beanutils包,里面就提供了许多实际开发中的应用场景会用到的API,大家不妨可以试用看看。
# 注意事项 开头提到JavaBean的get/set方法名要遵循某种规则,即驼峰规则。如下,我们将某个属性的get方法换个名字,例如将id属性的get方法名改为getUid()。那么我们就获取不到属性id的读方法的,即取到的是null。因为在取得id这个属性的属性描述器时,我们获取到了属性名,但是因为get方法没有遵循规则,所以调用`getReadMethod()`获取不到方法,所以出现空指针。 ![在这里插入图片描述](https://ucc.alicdn.com/images/user-upload-01/20210323154141277.png?1x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L2NoZW5saXhpYW8wMDc=,size_16,color_FFFFFF,t_70)
相关文章
|
11天前
|
Java 数据库连接 开发者
Java的Shutdown Hook机制:优雅地关闭应用程序
Java的Shutdown Hook机制:优雅地关闭应用程序
18 1
|
22天前
|
缓存 前端开发 安全
java的双亲委派机制
java的双亲委派机制
23 5
|
13天前
|
Java 程序员 开发者
深入理解Java并发编程:线程同步与锁机制
【4月更文挑战第30天】 在多线程的世界中,确保数据的一致性和线程间的有效通信是至关重要的。本文将深入探讨Java并发编程中的核心概念——线程同步与锁机制。我们将从基本的synchronized关键字开始,逐步过渡到更复杂的ReentrantLock类,并探讨它们如何帮助我们在多线程环境中保持数据完整性和避免常见的并发问题。文章还将通过示例代码,展示这些同步工具在实际开发中的应用,帮助读者构建对Java并发编程深层次的理解。
|
15天前
|
Java
【专栏】Java反射机制,该机制允许程序在运行时获取类信息、动态创建对象、调用方法和访问属性
【4月更文挑战第27天】本文探讨了Java反射机制,该机制允许程序在运行时获取类信息、动态创建对象、调用方法和访问属性。反射通过Class、Constructor、Method和Field类实现。文中列举了反射的应用场景,如动态创建对象、调用方法、访问属性和处理注解,并提供了相关实例代码演示。
|
1天前
|
安全 Java 数据安全/隐私保护
Java一分钟之-Java反射机制:动态操作类与对象
【5月更文挑战第12天】本文介绍了Java反射机制的基本用法,包括获取Class对象、创建对象、访问字段和调用方法。同时,讨论了常见的问题和易错点,如忽略访问权限检查、未捕获异常以及性能损耗,并提供了相应的避免策略。理解反射的工作原理和合理使用有助于提升代码灵活性,但需注意其带来的安全风险和性能影响。
13 4
|
3天前
|
Java 数据安全/隐私保护
java中异常处理机制
java中异常处理机制
11 1
|
4天前
|
算法 安全 Java
深入探索Java中的并发编程:CAS机制的原理与应用
总之,CAS机制是一种用于并发编程的原子操作,它通过比较内存中的值和预期值来实现多线程下的数据同步和互斥,从而提供了高效的并发控制。它在Java中被广泛应用于实现线程安全的数据结构和算法。
19 0
|
4天前
|
Java API 开发者
解密Java反射机制与动态代理
解密Java反射机制与动态代理
9 0
|
6天前
|
Java 数据库连接 开发者
Java中的异常处理机制详解
Java异常处理是确保程序健壮的关键,涉及Throwable的Error和Exception子类。Error由JVM抛出,不建议捕获;Exception分为检查异常(需要捕获)和未检查异常。处理异常的关键字有try、catch、finally、throw和throws。最佳实践包括捕获具体异常、不吞没异常、释放资源和避免滥用异常。示例展示了如何在main方法中处理IOException,并在finally块中进行资源清理。
10 1
|
11天前
|
缓存 NoSQL Java
17:缓存机制-Java Spring
17:缓存机制-Java Spring
23 5