March 18, 2010

Get metadata from JPA entities

I needed to extract a column length from a EJB-JPA Entity configured with annotations, this is how I did it:
import javax.persistence.Column;
import javax.persistence.Entity;

@Entity
public class Person {

   @Column(length=30)
   private String firstName;

   public static void main(String[] args) throws SecurityException,     NoSuchFieldException {
      Object person = new Person();
      println(person.getClass().getDeclaredField("firstName").getAnnotation(Column.class).length());
   }
}

Solution source