【问题标题】:How can I get a generic type annotation [closed]如何获得泛型类型注释 [关闭]
【发布时间】:2021-05-13 08:00:20
【问题描述】:

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

示例:我有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;
    }
}

【问题讨论】:

标签: java reflection java-annotations


【解决方案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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-03-18
    • 2021-07-14
    • 1970-01-01
    • 2023-03-11
    • 2011-03-27
    相关资源
    最近更新 更多