Java反射调用get/set方法,你还在这样用?

之前有些场景下碰到需要用到反射调用JavaBean的get/set方法时都是像以下这种拼接的方式来实现方法的调用。

Article article = new Article(); article.setTitle("这是标题"); article.setPublishTime(LocalDateTime.now()); Class<? extends Article> aClass = article.getClass(); Field[] declaredFields = aClass.getDeclaredFields(); for (Field declaredField : declaredFields) { String name = declaredField.getName(); String getMethodName = "get" + name.substring(0, 1).toUpperCase(Locale.ROOT) + name.substring(1); try { Method method = aClass.getMethod(getMethodName); Object invoke = method.invoke(article); System.out.println(name + "=" + invoke); } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) { e.printStackTrace(); } }

发现上面这种方式只能拿到当前类的属性,想要拿父类的属性还得自己写循环实现。
image

今天发现一个类Introspector可以获取一个BeanInfo,然后从BeanInfo上获取属性描述符PropertyDescriptor,然后就可以遍历调用其中的readMethodwriteMethod方法来实现对JavaBean的get/set方法调用,具体代码如下。

try { BeanInfo beanInfo = Introspector.getBeanInfo(article.getClass()); PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors(); Arrays.stream(propertyDescriptors) .filter(p -> !"class".equals(p.getName())) .forEach(pd -> { try { Method readMethod = pd.getReadMethod(); Object invoke = readMethod.invoke(article); System.out.println(pd.getName() + "=" + invoke); } catch (IllegalAccessException | InvocationTargetException e) { e.printStackTrace(); } }); } catch (IntrospectionException e) { e.printStackTrace(); }

这种方式还会自动把父类的属性也会列出来。如果将上面的filter拿掉会发现多了一个class属性,所以平常使用的时候需要过滤掉class属性。
image


__EOF__

本文作者余晖脉脉
本文链接https://www.cnblogs.com/lvbok/p/16995804.html
关于博主:评论和私信会在第一时间回复。或者直接私信我。
版权声明:本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!
声援博主:如果您觉得文章对您有帮助,可以点击文章右下角推荐一下。您的鼓励是博主的最大动力!
posted @   余晖脉脉  阅读(1406)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
· 字符编码:从基础到乱码解决
· 提示词工程——AI应用必不可少的技术
点击右上角即可分享
微信分享提示