双括号初始化中的方法参数?

时间:2013-07-24 23:35:03

标签: java method-parameters double-brace-initialize

我正在函数中创建一个带有双括号的HashMap内联:

public void myFunction(String key, String value) {
    myOtherFunction(
        new JSONSerializer().serialize(
            new HashMap<String , String>() {{
                put("key", key);
                put("value", value.);
            }}
        )
    );
}

我收到这些错误:

myClass.java:173: error: local variable key is accessed from within inner class; needs to be declared final
                        put("key", key);
                                   ^
myClass.java:174: error: local variable value is accessed from within inner class; needs to be declared final
                        put("value", value);
                                     ^
2 errors

如何将方法参数插入到初始化的Object双括号中?

2 个答案:

答案 0 :(得分:3)

将参数声明为final

public void myFunction(final String key, final String value)

另外,您可能需要查看Efficiency of Java "Double Brace Initialization"?

答案 1 :(得分:1)

如果你在内部类中使用非最终局部变量,编译器会抱怨,修复它:

public void myFunction(final String key, final String value) {
    myOtherFunction(
        new JSONSerializer().serialize(
            new HashMap<String , String>() {{
               put("key", key);
               put ("value", value.);
            }}
        )
    );
}