使用enum作为注释

时间:2017-02-17 00:01:55

标签: java

我有一个枚举:

public enum Vehicle {
  CAR,
  BUS,
  BIKE,
}

我打算将这些枚举值用作注释:@ Vehicle.CAR,@ Vehicle.BUS,@ Vehicle.BIKE。 java允许我将它们定义为注释吗?

2 个答案:

答案 0 :(得分:2)

不,你不能这样做。但是如果你想在注释中使用枚举,你可以这样做

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();
}

答案 1 :(得分:2)

您无法使用枚举作为注释。但是您可以将枚举添加为注释的元素。

枚举

public enum Priority { 
    LOW, 
    MEDIUM, 
    HIGH 
}

注释

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

注释用法

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