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!
Share
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: