Get rid of "The value for annotation attribute must be a constant expression" message

JavaAnnotations

Java Problem Overview


I use annotation in my code, and I try to use value which determine in run time.

I define my list as static final (lst), and I add to this list some elements.

When I use lst.get(i), I get compilation error:

The value for annotation attribute must be a constant expression

What is the solution for this issue?

Java Solutions


Solution 1 - Java

The value for an annotation must be a compile time constant, so there is no simple way of doing what you are trying to do.

See also here: https://stackoverflow.com/questions/2065937/how-to-supply-value-to-an-annotation-from-a-constant-java?rq=1

It is possible to use some compile time tools (ant, maven?) to config it if the value is known before you try to run the program.

Solution 2 - Java

This is what a constant expression in Java looks like:

package com.mycompany.mypackage;

public class MyLinks {
  // constant expression
  public static final String GUESTBOOK_URL = "/guestbook";
}

You can use it with annotations as following:

import com.mycompany.mypackage.MyLinks;

@WebServlet(urlPatterns = {MyLinks.GUESTBOOK_URL})
public class GuestbookServlet extends HttpServlet {
  // ...
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionConsView Question on Stackoverflow
Solution 1 - Javazw324View Answer on Stackoverflow
Solution 2 - JavaBenny NeugebauerView Answer on Stackoverflow