0

Please tell me, how can I get annotations for a generic type?

Example: I have public List<@NotNull GuestForm> guests and I want to get NotNull annotation.

public class BookingForm {
    public List<@NotNull GuestForm> guests;

    private List<String> amenities;

    private String propertyType;

    private Unrelated unrelated;

    public BookingForm(List<GuestForm> guests, List<String> amenities, String propertyType, Unrelated unrelated) {
        this.guests = guests;
        this.amenities = amenities;
        this.propertyType = propertyType;
        this.unrelated = unrelated;
    }
}
kaya3
  • 47,440
  • 4
  • 68
  • 97

1 Answers1

1
public class BookingForm {
    public List<@NotNull GuestForm> guests;

    private List<String> amenities;

    private String propertyType;

    private Unrelated unrelated;

    public BookingForm(List<GuestForm> guests, List<String> amenities, String propertyType, Unrelated unrelated) {
        this.guests = guests;
        this.amenities = amenities;
        this.propertyType = propertyType;
        this.unrelated = unrelated;
    }
}
Object objectClass = requireNonNull(bookingForm); 
var fields = objectClass.getClass().getDeclaredFields(); // Object fields
var annotations = ((AnnotatedParameterizedType) fields [0].getAnnotatedType()).getAnnotatedActualTypeArguments()[0].getAnnotations(); // Annotations of Generic type in List