views:

505

answers:

2

Hello,

I need to get the value of a field with a specific annotation, So with reflection I am able to get this Field Object. The problem is that this field will be always private though I know in advance it will always have a getter method. I know that I can use setAccesible(true) and get its value (when there is no PermissionManager), though I prefer to invoke its getter method.

I know that I could look for the method by looking for "get+fieldName" (though I know for example for boolean fields are sometimes named as "is+fieldName").

I wonder if there is a better way to invoke this getter (many frameworks use getters/setters to access the attributes so maybe they do in another way).

Thanks

+2  A: 

The naming convention is part of the well-established JavaBeans specification and is supported by the classes in the java.beans package.

Michael Borgwardt
+7  A: 

I think that should point you towards the right direction:

import java.beans.*

for (PropertyDescriptor pd : Introspector.getBeanInfo(Foo.class).getPropertyDescriptors()) {
  if (pd.getReadMethod() != null && !"class".equals(pd.getName()))
    System.out.println(pd.getReadMethod().invoke(foo));
}

Note that you could create BeanInfo or PropertyDescriptor instances yourself, i.e. without using Introspector. However, Introspector does some caching internally witch is normally a Good Thing (tm). If you're happy without a cache, you can even go for

// TODO check for non-existing readMethod
Object value = new PropertyDescriptor("name", Person.class).getReadMethod().invoke(person);

However, there are a lot of libraries that extend and simplify the java.beans API. Commons BeanUtils is a well known example. There, you'd simply do:

Object value = PropertyUtils.getProperty(person, "name");

BeanUtils comes with other handy stuff. E.g. on-the-fly value conversion (object to string, string to object) to simplify setting properties from user input.

sfussenegger
+1 simply right ... totally right ;)
BalusC
@BalusC Saying that something doesn't exist is always risky. Doing so with certainty even more; It's extremely tempering to downvote, isn't it? :)
sfussenegger