How to access annotated, private properties of jpa-entities.
Hi there,
in a lot of spring data tutorials, a bean property is private and annotated with @Id. Now I want to call the getProperty function of the @Id annotated property. BUT it could be inherited!
java.lang.reflect.Field supports getAnnotations() but has no acces to inherited properties.
and java.beans.Introspector does only support getProperty functions for access the annotations.
So how can I get access to the private id value?
This example fails cause getField throws NoSuchFieldException for inherited properties:
Code:
public K findIdField(final T entity) throws IntrospectionException, IllegalAccessException, InvocationTargetException, NoSuchFieldException, SecurityException {
final PropertyDescriptor[] descriptors = Introspector.getBeanInfo(entity.getClass()).getPropertyDescriptors();
for (final PropertyDescriptor descriptor : descriptors) {
Field field= entity.getClass().getField(descriptor.getName());
final Annotation[] annotations = field.getAnnotations();
for (Annotation annotation : annotations) {
if (annotation.annotationType().equals(Id.class) || annotation.annotationType().equals(EmbeddedId.class)) {
@SuppressWarnings("unchecked")
final K value = (K) descriptor.getReadMethod().invoke(entity);
return value;
}
}
}
return null;
}