分配@Annotation枚举值

Ble*_*eek 16 java enums annotations

我建立

enum Restrictions{
  none,
  enumeration,
  fractionDigits,
  length,
  maxExclusive,
  maxInclusive,
  maxLength,
  minExclusive,
  minInclusive,
  minLength,
  pattern,
  totalDigits,
  whiteSpace;

  public Restrictions setValue(int value){
    this.value = value;
    return this;
  }
  public int value;
}
Run Code Online (Sandbox Code Playgroud)

所以我可以愉快地做这样的事情,这是完全合法的语法.

Restrictions r1 =
  Restrictions.maxLength.setValue(64);
Run Code Online (Sandbox Code Playgroud)

原因是,我使用枚举来限制可以使用的限制类型,并且能够为该限制分配值.

但是,我的实际动机是在@annotation中使用该限制.

@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE, ElementType.FIELD, ElementType.METHOD})
public @interface Presentable {
  Restrictions[] restrictions() default Restrictions.none;
}
Run Code Online (Sandbox Code Playgroud)

所以,我打算这样做:

@Presentable(restrictions=Restrictions.maxLength.setValue(64))
public String userName;
Run Code Online (Sandbox Code Playgroud)

对此,编译器呱呱叫

The value for annotation enum attribute must be an enum constant expression.
Run Code Online (Sandbox Code Playgroud)

有没有办法完成我想要完成的任务

Abh*_*kar 27

你可以这样做:

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

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();
}
Run Code Online (Sandbox Code Playgroud)