如何使用注释表示参数化类型



我尝试使用注释处理器生成类似的方法:

void result(Consumer<Type> name){
}

我需要使用注释来表示参数。

@Retention(RetentionPolicy.SOURCE)
public @interface Parameter {
  String name();
  Class<?> type();
}

但是注释成员仅支持编译时常数,因此不可能直接传递参数化类型,例如,以下非法Java代码无法通过注释表示。

@Parameter(name ="ids",type = ArrayList<Integer>.class)

我试图声明一个新的注释来表示类型,因为通用参数可以是一个或多个嵌套,例如ArrayList <HashMap <String, String >>,但是Java不支持注释本身,它将导致环保注释元素类型错误。以下注释也是非法的。

public @interface Type{
  Class<?> type();
  Type[] parameters() default {};
}
@Retention(RetentionPolicy.SOURCE)
public @interface Parameter {
  String name();
  Type type();
}

有什么解决方案?

当您无法将值表示为注释参数时,标准解决方案是使用字符串。例如,使用@Parameter(..., type = ArrayList<Integer>.class)而不是@Parameter(..., type = "ArrayList<Integer>"),它可以代表任意嵌套的参数化类型。

使用注释的代码必须对字符串参数进行解析和验证。

最新更新