mercredi 1 mars 2017

Java. How to get non-nullable fields by reflection?

I try to get list of fields from class (hibernate entity). Like this:

Entity:

public class A {

    public static final Integer someValue = 1;

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "a_id")
    private Integer id;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "a_b_id", nullable = true)
    private List<B> b;

    @NotNull
    @Column(name = "a_c_id")
    private C c;

    .........................
}

Method for getting non-static fields:

public static List<Field> getNonStaticFields(Class clazz) {
    Field[] fields = clazz.getDeclaredFields();
    List<Field> fieldsList = new ArrayList<>();
    for (Field field : fields) {
        if (!Modifier.isStatic(field.getModifiers())) {
            fieldsList.add(field);
        }
    }

    return fieldsList;
}

But I need to get only non-nullable non-static fields. This means that I need to get fields with @NotNull annotation and @JoinColumn annotation with parameter "nullable = false".

Check for @NotNull is simple:

field.isAnnotationPresent(NotNull.class)

But I have no idea how can I check field for @JoinColumn with parameter. How can I do it? Can somebody help me?





Aucun commentaire:

Enregistrer un commentaire