How can I get a list of all the private properties of Java object used in getters and setters. I tried PropertyUtils
and MethodUtils
but no luck. Now I am trying to use getDeclaredFields()
of the Class object which returns me a list of Field objects and then check if that is a private property is that a way to go? Or are there any better solutions to this.

- 19,879
- 23
- 80
- 93
4 Answers
This is quite old question post but i'll provide an answer here for the sake of new searches.
Using the approach provided by @highlycaffeinated here: https://stackoverflow.com/a/6796254/776860
You can easily come up with a desired solution with a couple of changes.
Retrieving a list of private field names only
public List<String> getMap(Object o) throws IllegalArgumentException, IllegalAccessException {
List<String> result = new ArrayList<String>();
Field[] declaredFields = o.getClass().getDeclaredFields();
for (Field field : declaredFields) {
if(!field.isAccessible()) {
result.add(field.getName());
}
}
return result;
}
Retrieving a Map of all field names and their values
public Map<String, Object> getMap(Object o) throws IllegalArgumentException, IllegalAccessException {
Map<String, Object> result = new HashMap<String, Object>();
Field[] declaredFields = o.getClass().getDeclaredFields();
for (Field field : declaredFields) {
field.setAccessible(true);
result.put(field.getName(), field.get(o));
}
}
return result;
}
Exactly like @highlycaffeinated provided just with the additional line field.setAccessible(true);
which enables you to introspect private
fields too.
What you said, or maybe yourBean.getClass().getMethods()
and then method.getName().startsWith("get")
on each method returned.
May I ask why you need to do this for?

- 7,915
- 9
- 39
- 60
-
1I have a few custom properties for a Java class coming in from the request which needs to get into a hashmap (it's one of the property). And this object is a type parameter so I am using reflection to create and populate this object. – Vishal Nov 10 '11 at 22:59
You could look for all the getters and setters and look to see if there is a matching field. However fields can start with _fieldName
or m_fieldName
You can only infer the getters/setters has something to do with the field.

- 525,659
- 79
- 751
- 1,130
I am doing this:
private Set<String> getModelProperties(Class<T> cls) {
Set<String> properties = new HashSet<String>();
for (Method method : cls.getDeclaredMethods()) {
String methodName = method.getName();
if (methodName.startsWith("set")) {
properties.add(Character.toLowerCase(
methodName.charAt(0)) + methodName.substring(3));
}
}
return properties;
}

- 19,879
- 23
- 80
- 93