如何为自己的注释创建可选参数?

2022-08-31 10:32:43

以下是注释代码

public @interface ColumnName {
   String value();
   String datatype();
 }

我想做一个可选参数,例如datatype

@ColumnName(value="password") 

应该是有效的代码。


答案 1

似乎官方文档中的第一个例子说明了一切...

/**
 * Describes the Request-For-Enhancement(RFE) that led
 * to the presence of the annotated API element.
 */
public @interface RequestForEnhancement {
    int    id();
    String synopsis();
    String engineer() default "[unassigned]"; 
    String date()     default "[unimplemented]"; 
}

答案 2

要使其成为可选的,您可以为其分配一个默认值,如下所示:

public @interface ColumnName {
   String value();
   String datatype() default "String";
 }

然后,在使用批注时不需要指定它。


推荐