[英]How can I use annotations to represent a parameterized type?
I trying to using annotation processor to generate some methods like that: 我试图使用注释处理器来生成类似这样的方法:
void result(Consumer<Type> name){
}
Than I need to using a annotation to represent a parameter. 比我需要使用注释来表示参数。
@Retention(RetentionPolicy.SOURCE)
public @interface Parameter {
String name();
Class<?> type();
}
But the annotation members only support compile-time constants, so it is impossible to delivery a parameterized type directly, for example the following illegal java code can't be represent by annotation. 但是注解成员仅支持编译时常量,因此无法直接传递参数化类型,例如,以下非法Java代码不能由注解表示。
@Parameter(name ="ids",type = ArrayList<Integer>.class)
I tried to declare a new annotation to represent the type, because the generic parameters can be one or more and nested, such as ArrayList <HashMap <String, String >>
, but java does not support annotations reference itself, it will cause cyclic annotation element type error. 我试图声明一个新的注释来表示类型,因为通用参数可以是一个或多个并嵌套,例如ArrayList <HashMap <String, String >>
,但是java不支持注释本身,它将导致循环注释元素类型错误。 the following annotation is illegal too. 以下注释也是非法的。
public @interface Type{
Class<?> type();
Type[] parameters() default {};
}
@Retention(RetentionPolicy.SOURCE)
public @interface Parameter {
String name();
Type type();
}
Any solutions? 有什么办法吗?
When you cannot represent a value as an annotation argument, the standard solution is to use a string instead. 当您不能将值表示为注释参数时,标准解决方案是改用字符串。 For example, instead of @Parameter(..., type = ArrayList<Integer>.class)
, use @Parameter(..., type = "ArrayList<Integer>")
, which can represent arbitrarily-nested parameterized types. 例如,使用@Parameter(..., type = "ArrayList<Integer>")
代替@Parameter(..., type = ArrayList<Integer>.class)
@Parameter(..., type = "ArrayList<Integer>")
,它可以表示任意嵌套的参数化类型。
Your code that uses the annotations must do parsing and validation of the String argument. 您使用注释的代码必须对String参数进行解析和验证。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.