如何获得泛型类型注释

时间:2021-02-09 16:40:39

标签: java java-annotations java-reflection

请告诉我,如何获得泛型类型的注释?

示例:我有 public List<@NotNull GuestForm> guests 并且我想获得 NotNull 注释。

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;
    }
}

1 个答案:

答案 0 :(得分: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