为@Annotation枚举分配一个值 [英] Assigning an @Annotation enum a value
本文介绍了为@Annotation枚举分配一个值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我创建了
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;
}
这样我可以很高兴地做这样的事情,这是完全合法的语法.
So that I could happily do something like this, which is perfectly legal syntax.
Restrictions r1 =
Restrictions.maxLength.setValue(64);
原因是,我正在使用枚举限制可以使用的限制类型,并能够为该限制分配一个值.
The reason being is, I am using enum to restrict the type of restriction that could be used, and be able to assign a value to that restriction.
但是,我的实际动机是在@annotation中使用该限制.
However, my actual motivation is to use that restriction in an @annotation.
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE, ElementType.FIELD, ElementType.METHOD})
public @interface Presentable {
Restrictions[] restrictions() default Restrictions.none;
}
因此,我打算这样做:
@Presentable(restrictions=Restrictions.maxLength.setValue(64))
public String userName;
编译器发出的嘶哑声
The value for annotation enum attribute must be an enum constant expression.
有没有办法完成我想完成的事情
Is there a way to accomplish what I wish to accomplish
推荐答案
您可以这样做:
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();
}
这篇关于为@Annotation枚举分配一个值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文