4

Are there any java libraries which allow me to utilize BeanUtils like property access bean.prop1.prop2 while allowing access to the annotations on the getter/field itself?

For example, I have a bean class that looks like this:

public class Child {
  @SomeCustomAnnotation
  private String name;
  //standard bean getter setters
  }

public class Parent {
  private Child child;
  //standard bean getter setters
}

And I would like to be able to retrieve not only the value of the property I'm looking for but also any annotations annotated on that field that's value is being returned:

String childsName = SomeLibrary.getValue(parent, "child.name");
Annotation[] annotationsOnChildsName = SomeLibrary.getAnnotations(parent, "child.name");

Do any libraries exist which allow both features? I can use Commons BeanUtils to do pure property access for values and Plain Reflection to get the annotations on properties, but there doesn't seem to be a way to combine both abilities.

1 Answer 1

3

Unless I am missing something you can just the reflection's Field class

Field f = Parent.class.getField("name");
Object value = f.get(parent);
f.getAnnotations();
3
  • 1
    The nuance here is I would like to be able to support access through standard java bean conventions (ie. getName() and the field name) as well as nested properties Nov 2, 2011 at 15:45
  • I was thinking about this and not sure this is really possible, ie: you could only do it based on convention. For example, my private field may not be named the same as the getter setter or even be the same type. Nov 3, 2011 at 4:22
  • getField only gives publicly accessible field, use getDeclaredField to obtain protected fields
    – gerrytan
    Jul 1, 2013 at 6:28

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.