Java 摆脱“注释属性的值必须是常量表达式”消息

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16509065/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-16 07:13:07  来源:igfitidea点击:

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

javaannotations

提问by Cons

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.

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

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

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

The value for annotation attribute must be a constant expression

What is the solution for this issue?

这个问题的解决方案是什么?

采纳答案by zw324

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

另请参见此处:如何从常量 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.

如果在您尝试运行程序之前已知该值,则可以使用一些编译时工具(ant、maven?)来配置它。

回答by Benny Neugebauer

This is what a constant expression in Java looks like:

这是 Java 中的常量表达式的样子:

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