ChatGPT解决这个技术问题 Extra ChatGPT

How to create optional parameters for own annotations?

Following is the annotation code

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

I would like to make datatype an optional parameter, for example

@ColumnName(value="password") 

should be a valid code.


S
Steve Chambers

Seems like the first example in the official documentation says it all ...

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

i only looked at the tutorials.ie why i couldnt find this.may i know the difference between unassigned and unimplemented
There is not difference. They're just String values. They could be "peter" and "paul".
And what if my params are Class<?>s?
In that case, Java's type system still applies. For example Class<?> proxy() default Object.class
Thanks! The official documentation may have the example, but this SO post was the top hit on my Goggle search so your response and the link are helpful!
J
Johannes Wachter

To make it optional you can assign it a default value like that:

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

Then it doesn't need to be specified when using the Annotation.