0

How do I pass string variable to an annotated class, where the String variable is present in a properties file?

I'm seeing the error message: The value for annotation attribute Example.localID must be a constant

For Example consider below annoated interface

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public @interface Example {

  String localID() default "";
}

I have created a class 'ExampleService' which is annotated with 'Example' interface as shown below

I like to provides values for localID as 'localID=Messages.TITLE' as shown below.

Currently this not possible to provides values like this because of compilation error, is there any way to solve this issue or alternative(I donot want to make final because values get changed depending on local) ?

'Messages.TITLE' values comes from property file.

@Example(localID=Messages.TITLE)
public class ExampleService {
}

class:Messages

public class Messages extends NLS {

    public static String        TITLE;
    private static final String BUNDLE_NAME = "xyz"; //$NON-NLS-1$

    static {

        NLS.initializeMessages(BUNDLE_NAME, Messages.class);
    }
private Messages() {
}
activedecay
  • 10,129
  • 5
  • 47
  • 71
Ganesh Rao B
  • 461
  • 2
  • 8
  • 23
  • include the compilation error. remove the extraneous code, try to duplicate the error using as few codelines as possible. http://idownvotedbecau.se/nomcve/ – activedecay Mar 19 '18 at 05:52
  • your question may be a duplicate of https://stackoverflow.com/questions/2065937/how-to-supply-value-to-an-annotation-from-a-constant-java#2067863 – activedecay Mar 19 '18 at 05:55
  • No its not duplicate of above question – Ganesh Rao B Mar 19 '18 at 06:18
  • then perhaps this is the duplicate https://stackoverflow.com/questions/16509065/get-rid-of-the-value-for-annotation-attribute-must-be-a-constant-expression-me?noredirect=1&lq=1 – activedecay Mar 19 '18 at 15:39

1 Answers1

0

Constant in JAVA means values determined during compiling. Strings in properties are not constant. So Messages.TITLE, whether or not with final, cannot be used as Annotation's attribute value if it comes from properties.

IMHO, you should think carefully the reason of using a changeable value as Annotation's attribute.

For alternation, maybe you can use class as the attribute, with the Annotation:

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public @interface Example {

  Class localID();
}

And the ExampleService like

@Example(localID=Messages.class)
public class ExampleService {
}

At the place you actually use localID, use reflect to retrieve the value of Title.

John
  • 1,654
  • 1
  • 14
  • 21