2

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

  • aClassName is the name of a class in my application
  • anAttribute is one of it's attributes which is a String:

    public static String anAttribute1="aStringxxx";

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

3
  • 2
    Make the attribute final. Commented May 8, 2013 at 14:27
  • Did you mean to make value a String[] rather than String ? Commented May 8, 2013 at 14:37
  • Thank you ^^ I added final to the attribute and the error desappeared! Commented May 8, 2013 at 15:01

3 Answers 3

2

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;
}
Sign up to request clarification or add additional context in comments.

Comments

1

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

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

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.