ChatGPT解决这个技术问题 Extra ChatGPT

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

以下是注释代码

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

我想让 datatype 成为可选参数,例如

@ColumnName(value="password") 

应该是有效的代码。


S
Steve Chambers

似乎 official documentation 中的第一个示例说明了一切......

/**
 * 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]"; 
}

我只看了教程。即为什么找不到这个。我可以知道未分配和未实现之间的区别
没有区别。它们只是字符串值。他们可能是“彼得”和“保罗”。
如果我的参数是 Class<?> 怎么办?
在这种情况下,Java 的类型系统仍然适用。例如 Class<?> proxy() default Object.class
谢谢!官方文档可能有这个例子,但是这篇 SO 帖子是我的 Goggle 搜索的热门文章,所以你的回复和链接很有帮助!
J
Johannes Wachter

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

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

那么在使用Annotation的时候就不需要指定了。