Annotation reflection (using getAnnotation) does not work
annotations, java, jpa, persistence, reflection
Solution
- `property` represents a class (it's a `Class<?>`)
- `@Column` and `@JoinColumn` can only annotate fields/methods.
Consequently you will never find these annotations on `property`.
A slightly modified version of your code that prints out whether the email property of the Employee entity is required:
public static void main(String[] args) throws NoSuchFieldException {
System.out.println(isRequired(Employee.class, "email"));
}
private static boolean isRequired(Class<?> entity, String propertyName) throws NoSuchFieldException {
Field property = entity.getDeclaredField(propertyName);
final JoinColumn joinAnnotation = property.getAnnotation(JoinColumn.class);
if (null != joinAnnotation) {
return !joinAnnotation.nullable();
}
final Column columnAnnotation = property.getAnnotation(Column.class);
if (null != columnAnnotation) {
return !columnAnnotation.nullable();
}
return false;
}
Note that this is a half-baked solution, because JPA annotations can either be on a field or on a method. Also be aware of the difference between the reflection methods like `getFiled()`/`getDeclaredField()`. The former returns inherited fields too, while the latter returns only fields of the specific class ignoring what's inherited from its parents.
Problem
I have to following code to check whether the entity in my `model` has a `nullable=false` or similar annotation on a field. ``` import javax.persistence.Column; import ..... private boolean isRequired(Item item, Object propertyId) { Class<?> property = getPropertyClass(item, propertyId); final JoinColumn joinAnnotation = property.getAnnotation(JoinColumn.class); if (null != joinAnnotation) { return !joinAnnotation.nullable(); } final Column columnAnnotation = property.getAnnotation(Column.class); if (null != columnAnnotation) { return !columnAnnotation.nullable(); } .... return false; } ``` Here's a snippet from my model. ``` import javax.persistence.*; import ..... @Entity @Table(name="m_contact_details") public class MContactDetail extends AbstractMasterEntity implements Serializable { @Column(length=60, nullable=false) private String address1; ``` For those people unfamiliar with the `@Column` annotation, here's the header: ``` @Target({METHOD, FIELD}) @Retention(RUNTIME) public @interface Column { ``` I'd expect the `isRequired` to return `true` every now and again, but instead it never does. I've already done a `mvn clean` and `mvn install` on my project, but that does not help. Q1: What am I doing wrong? Q2: is there a cleaner way to code `isRequired` (perhaps making better use of generics)?