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

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


# 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)
相关文章
|
2天前
|
Java 数据库
JAVA并发编程-一文看懂全部锁机制
曾几何时,面试官问:java都有哪些锁?小白,一脸无辜:用过的有synchronized,其他不清楚。面试官:回去等通知! 今天我们庖丁解牛说说,各种锁有什么区别、什么场景可以用,通俗直白的分析,让小白再也不怕面试官八股文拷打。
|
3天前
|
Java 程序员 开发者
Java中的异常处理机制深度解析
本文旨在深入探讨Java中异常处理的核心概念与实际应用,通过剖析异常的本质、分类、捕获及处理方法,揭示其在程序设计中的关键作用。不同于常规摘要,本文将直接切入主题,以简明扼要的方式概述异常处理的重要性及其在Java编程中的应用策略,引导读者快速把握异常处理的精髓。
|
9天前
|
Java 程序员 数据库连接
Java中的异常处理机制:从基础到高级
【9月更文挑战第10天】在Java的世界,异常是程序运行过程中的不速之客。它们悄无声息地潜入,威胁着代码的健康执行。了解并掌握Java的异常处理机制,就如同为程序穿上了一件护身符,让这些意外的访客不再成为灾难。本文将引导你走进Java异常处理的大门,从简单的try-catch语句到自定义异常类的创建,再到finally块的使用和异常链的形成,让你的程序在面对异常时能优雅地起舞。
|
2天前
|
安全 Java 开发者
Java并发编程中的锁机制解析
本文深入探讨了Java中用于管理多线程同步的关键工具——锁机制。通过分析synchronized关键字和ReentrantLock类等核心概念,揭示了它们在构建线程安全应用中的重要性。同时,文章还讨论了锁机制的高级特性,如公平性、类锁和对象锁的区别,以及锁的优化技术如锁粗化和锁消除。此外,指出了在高并发环境下锁竞争可能导致的问题,并提出了减少锁持有时间和使用无锁编程等策略来优化性能的建议。最后,强调了理解和正确使用Java锁机制对于开发高效、可靠并发应用程序的重要性。
11 3
|
5天前
|
Java 开发者
Java中的异常处理机制
本文将深入探讨Java中异常处理的基本概念和机制,包括try-catch-finally块、throws关键字以及自定义异常类的使用方法。我们将通过实例演示如何在Java程序中有效地捕获和处理异常,确保程序的健壮性和稳定性。无论您是Java编程的初学者还是有一定经验的开发者,本文都能为您提供有价值的参考。
|
3天前
|
Java 编译器 开发者
Java中的异常处理机制:从基础到高级应用
在Java编程中,异常处理是一个至关重要的部分,它帮助开发者处理运行时错误,确保程序的鲁棒性和可靠性。本文将深入探讨Java异常处理的基础和高级应用,包括异常的分类、捕获和处理方法,以及如何使用自定义异常和异常链。通过实际案例,我们将展示如何有效利用Java的异常处理机制来提升代码质量。
|
7天前
|
Java 程序员 开发者
探索Java中的异常处理机制
【9月更文挑战第12天】在Java编程世界中,异常处理是一块不可或缺的拼图。本文将带领读者深入理解Java的异常处理机制,从基本概念到高级用法,一探究竟。我们将通过实际代码示例,展示如何捕获和处理异常,以及如何自定义异常来增强程序的健壮性。无论你是Java新手还是资深开发者,这篇文章都将为你提供有价值的见解和技巧。
|
6天前
|
Java 开发者
深入解析Java中的异常处理机制
本文将深入探讨Java中异常处理的核心概念和实际应用,包括异常的分类、捕获、处理以及最佳实践。我们将通过具体示例展示如何有效使用try-catch块、throws关键字和自定义异常类,以帮助读者更好地理解和应用Java异常处理机制。
11 1
|
6天前
|
Java 数据库连接 开发者
Java中的异常处理机制:理解与应用
在Java编程中,异常处理是一个核心概念,它允许程序在遇到错误时优雅地恢复或终止。本文将深入探讨Java的异常处理机制,包括异常的分类、如何正确使用try-catch-finally块以及throw关键字。我们将通过实例来说明如何在Java应用程序中有效地捕获和处理异常,以确保程序的健壮性和稳定性。
|
6天前
|
Java 程序员 开发者
Java中的异常处理机制深度解析
本文旨在深入探讨Java中异常处理的机制,包括异常的分类、如何捕获和处理异常,以及自定义异常的最佳实践。通过实例讲解,帮助读者更好地理解如何在Java编程中有效管理和利用异常处理来提高代码的健壮性和可维护性。