我正在函数中创建一个带有双括号的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
双括号中?
答案 0 :(得分:3)
将参数声明为final
:
public void myFunction(final String key, final String value)
答案 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.);
}}
)
);
}