Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

java custom annotation: make an attribute optional

I defined my own custom annotation

@Target(value={ElementType.METHOD, ElementType.FIELD}) @Retention(RetentionPolicy.RUNTIME) public @interface MyCustomAnnotation  {     Class<?> myType(); } 

how, if at all, can I make the attribute optional

like image 373
flybywire Avatar asked Aug 31 '09 15:08

flybywire


People also ask

What is @interface annotation in Java?

@interface is used to create your own (custom) Java annotations. Annotations are defined in their own file, just like a Java class or interface. Here is custom Java annotation example: @interface MyAnnotation { String value(); String name(); int age(); String[] newNames(); }

Can we create custom annotations Java?

Java Custom annotations or Java User-defined annotations are easy to create and use. The @interface element is used to declare an annotation. For example: @interface MyAnnotation{}

What is @target annotation in Java?

If an @Target meta-annotation is present, the compiler will enforce the usage restrictions indicated by ElementType enum constants, in line with JLS 9.7. 4. For example, this @Target meta-annotation indicates that the declared type is itself a meta-annotation type.


1 Answers

You can provide a default value for the attribute:

@Target(value={ElementType.METHOD, ElementType.FIELD}) @Retention(RetentionPolicy.RUNTIME) public @interface MyCustomAnnotation  {     Class<?> myType() default Object.class; } 
like image 69
Dan Dyer Avatar answered Oct 05 '22 14:10

Dan Dyer