有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

在Java中强制将通用接口作为注释的值

有没有办法在Java注释中接收泛型类型作为值

// The generics interface:
public interface TypeConverter<S, R> {
    public R convert(S sourceType); 
}

// The implementation:
public DateConverter extends TypeConverter<String, Date> {
    public String convert(Date sourceType) { ... }
}

// Applying the custom converter through an annotation on a field:
...
Converter(DateConverter.class);
public Date dateField;
...

// The issue! Receiving the generic type in an annotation value:
public @interface Converter {
    //How to use the generic type as the type of "value"?
    Class value() default void.class;
    // versus
    //Class<? extends TypeConverter> type() default void.class;
}

查看上面注释Converter上的注释


共 (1) 个答案

  1. # 1 楼答案

    没有办法做到这一点,但是,有一个解决办法,你可能会感兴趣

    如果不希望注释参数是必需的,并且无法传递默认值,则始终可以使用数组

    public @interface Converter {
      Class<? extends TypeConverter>[] type() default {};
    }
    //.. and the possible usages
    @Converter
    @Converter(type = FooConverter.class)
    @Converter(type = { FooConverter.class, ThisIsWhatCanHappen.class }) // this is the downside of this approach
    
    // retrieving type from annotation
    void foo(Converter converter) {
      TypeConverter typeConverter = converter.type().length > 0
        ? converter.type()[0]
        : null; // or some default value
      // now that you have your TypeConverter do a backflip or something
    }
    

    有两个缺点

    • 数组可以是任意长度,您无法控制它(这可能会让人困惑)
    • 使用起来稍微不太舒服,您必须检查数组是否为空,并让它的第一个元素访问type