简体   繁体   English

从函数生成常量表达式

[英]Generate a Constant expression from a function

For my Google Wave robot, on the onDocumentChanged event I want to apply a filter as follows: 对于我的Google Wave机器人,在onDocumentChanged事件上,我想应用一个过滤器,如下所示:

@Capability(filter = FILTER)
@Override
public void onDocumentChanged(DocumentChangedEvent event) {
    ...
}

I want the filter to be generated the first time the robot is run, which I'm trying to do as follows: 我希望在机器人第一次运行时生成过滤器,我试图这样做如下:

private static final String FILTER = generateFilter();

private static final String generateFilter(){
    ...
}

However, it complains FILTER isn't a constant expression when used within @Capability. 但是,它抱怨在@Capability中使用FILTER不是常量表达式。

generateFilter() will return the same string every time it is called, I'm only using it to create the string so that when I make changes, I don't need to worry about updating the filter. generateFilter()每次调用时都会返回相同的字符串,我只是用它来创建字符串,这样在进行更改时,我不必担心更新过滤器。

Now I could be going about this all wrong, so wondered if anyone knew what I'm doing wrong, or knew a better way in which I could generate a constant expression from the function. 现在,我可能会遇到所有错误,因此想知道是否有人知道我在做什么错,还是知道一种更好的方法可以从函数生成常量表达式。

I'm unfamiliar with Google Wave, but a static initializer might be acceptable, as shown here and outlined below. 我不熟悉谷歌Wave,但静态初始化是可以接受的,如在这里和概述如下。

private static final String FILTER;
static { FILTER = "..."; }

Addendum: On closer scrutiny, this approach is not possible, as an annotation value must be (among other things) a constant expression . 附录:在仔细推敲,这种方法是不可能的,作为注释值必须是(除了别的以外)一常量表达式

The compiler needs the contant value in the annotation at compile time and your initialization will happen i think at the application initialization time. 编译器在编译时需要注释中的contant值,我认为您的初始化将在应用程序初始化时进行。

You could probably do it like this: 您可能会这样做:

private static final String FILTER = "YOUR STRING";

private static final String generateFilter() {
   return FILTER;
}

That way if you need to change it and not worry you will go the the method and from there to the constant value :). 这样,如果您需要更改它而不必担心,则可以使用该方法,然后从那里到常量值:)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM