Java Reflection:如何获取java类的所有getter方法并调用它们
我编写了一个有很多 getter 的 java 类..现在我想获取所有 getter 方法并在某个时候调用它们..我知道有 getMethods() 或 getMethod(String name, Class...parameterTypes) 等方法,但我只是想真正获得吸气剂...,使用正则表达式?谁能告诉我?谢谢!
I write a java class which has many getters..now I want to get all getter methods and invoke them sometime..I know there are methods such as getMethods() or getMethod(String name, Class... parameterTypes) ,but i just want to get the getter indeed..., use regex? anyone can tell me ?Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
不要使用正则表达式,使用
Introspector< /code>
:
通常您不需要 Object.class 中的属性,因此您可以使用带有两个参数的方法:
顺便说一句:有些框架可以为您执行此操作并为您提供高级视图。例如
commons/beanutils 有方法
(docs here) 的作用就是:查找并执行所有 getter 并将结果存储在映射中。不幸的是,BeanUtils.describe() 在返回之前将所有属性值转换为字符串。 WTF。谢谢@danw
更新:
这是一个 Java 8 方法,它根据对象的 bean 属性返回
Map
。不过,您可能希望使错误处理更加健壮。对样板文件感到抱歉,检查的异常阻止我们在这里充分发挥作用。
事实证明 Collectors.toMap() 讨厌空值。这是上述代码的更命令式版本:
是使用 JavaSlang 以更简洁的方式实现相同功能的方式:
这 这是番石榴版本:
Don't use regex, use the
Introspector
:Usually you don't want properties from Object.class, so you'd use the method with two parameters:
BTW: there are frameworks that do that for you and present you a high-level view. E.g.
commons/beanutils has the method
(docs here) which does just that: find and execute all the getters and store the result in a map. Unfortunately,
BeanUtils.describe()
converts all the property values to Strings before returning. WTF. Thanks @danwUpdate:
Here's a Java 8 method that returns a
Map<String, Object>
based on an object's bean properties.You probably want to make error handling more robust, though. Sorry for the boilerplate, checked exceptions prevent us from going fully functional here.
Turns out that Collectors.toMap() hates null values. Here's a more imperative version of the above code:
Here's the same functionality in a more concise way, using JavaSlang:
And here's a Guava version:
您可以使用 Reflections 框架来实现此目的
You can use Reflections framework for this
Spring 提供了一个简单的 BeanUtil 方法 用于 Bean 自省:
Spring offers an easy BeanUtil method for Bean introspection:
为什么不使用简单的Java?
……
Why not use simple Java?
...
...
这段代码经测试OK。
This code is tested OK.