M810
M810

Reputation: 53

Error with custom annotation

I have made a custom annotation in java that takes one value (String[]);

@Retention(value = RetentionPolicy.RUNTIME)
public @interface MyAnnotation{
    String[] value ();
}

however, I want the values-when I use MyAnnotation-to be like this: aClassName.anAttribute

But I get an error: The value for annotation attribute MyAnnotation.value must be a constant expression Does anyone have an idea please?

Upvotes: 2

Views: 231

Answers (3)

maba
maba

Reputation: 48045

If you make the attribute final it will work just fine.

public class SomeClass {
    public static final String myAttribute = "abc";
}

@Retention(value = RetentionPolicy.RUNTIME)
public @interface MyAnnotation {
    String[] value();
}

public class SomeOtherClass {
    @MyAnnotation({SomeClass.myAttribute})
    private int someInt;
}

Upvotes: 2

Mel Nicholson
Mel Nicholson

Reputation: 3225

The solution is to mark anAttribute1 as a static final to make it a constant expression.

class MyAttributeConstants {
  public static final anAttribute1 = "someString";
}

Upvotes: 1

Puce
Puce

Reputation: 38122

I'm not sure if I understood your question correctly, but AFAIK you can not use constants which are defined in the same class that uses the annotation.

Possible solution: move the constants to a helper class

Upvotes: 0

Related Questions