删除“注释属性的值必须是一个常量表达式”消息

我在代码中使用注释,并尝试使用在运行时确定的值。

我将列表定义为 static final(lst) ,并在列表中添加一些元素。

当我使用 lst.get(i)时,会出现编译错误:

The value for annotation attribute must be a constant expression

这个问题的解决办法是什么?

202049 次浏览

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.

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 {
// ...
}