Bajji
Bajji

Reputation: 2393

Using enum as annotation

I have an enum :

public enum Vehicle {
  CAR,
  BUS,
  BIKE,
}

I intend to use these enum values as annotations : @Vehicle.CAR, @Vehicle.BUS, @Vehicle.BIKE. Does java allow me to define them as annotations ?

Upvotes: 1

Views: 3620

Answers (2)

Flood2d
Flood2d

Reputation: 1358

You can't use enum as annotations. But you can add the enum as an element of the annotation.

The enum

public enum Priority { 
    LOW, 
    MEDIUM, 
    HIGH 
}

The annotation

@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD})
public @interface TestAnnotation {
    Priority priority() default Priority.MEDIUM;
}

The annotation usage

@TestAnnotation(priority =  Priority.HIGH)
public void method() {
      //Do something  
}

Upvotes: 2

Bilal Shah
Bilal Shah

Reputation: 1265

No You can not do this. But if you want to use enum in annotation you can do like this

class Person {    
    @Presentable({
        @Restriction(type = RestrictionType.LENGTH, value = 5),
        @Restriction(type = RestrictionType.FRACTION_DIGIT, value = 2)
    })
    public String name;
}

enum RestrictionType {
    NONE, LENGTH, FRACTION_DIGIT;
}

@Retention(RetentionPolicy.RUNTIME)
@interface Restriction {
    //The below fixes the compile error by changing type from String to RestrictionType
    RestrictionType type() default RestrictionType.NONE;
    int value() default 0;
}

@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE, ElementType.FIELD, ElementType.METHOD})
@interface Presentable {
  Restriction[] value();
}

Upvotes: 4

Related Questions