Assigning an @Annotation enum a value
Posted
by h2g2java
on Stack Overflow
See other posts from Stack Overflow
or by h2g2java
Published on 2010-06-10T00:55:33Z
Indexed on
2010/06/10
1:02 UTC
Read the original article
Hit count: 297
I created
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.
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;
}
So that, I intended to do this:
@Presentable(restrictions=Restrictions.maxLength.setValue(64))
public String userName;
to which, the compiler croaks
The value for annotation enum attribute must be an enum constant expression.
Is there a way to accomplish what I wish to accomplish
© Stack Overflow or respective owner