Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 921
Cons Avatar asked May 12 '13 15:05

Cons


2 Answers

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: How to supply value to an annotation from a Constant java

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.

like image 141
zw324 Avatar answered Nov 07 '22 16:11

zw324


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 {
  // ...
}
like image 40
Benny Neugebauer Avatar answered Nov 07 '22 15:11

Benny Neugebauer