java - Set a local variable value from inside a lambda
问题描述
I have the following code:
public void visitStrAttribute(String attributeName, Consumer<String> attributeConsumer) {
IntConsumer intConsumer;
int stringByteArrayLength = 0;
visitIntAttribute("", (IntValue) -> stringByteArrayLength = IntValue);
attributeConsumer
.accept(new String(readInputStream(stringByteArrayLength), StandardCharsets.UTF_8));
}
I need to set stringByteArrayLength
inside the lambda but an error message appears and it told me Local variable stringByteArrayLength defined in an enclosing scope must be final or effectively final
.
How do I fix this?
解决方案
一种解决方案是使您的变量成为具有一个元素的最终数组,并修改其中的元素,如下所示:
final int[] stringByteArrayLength = {0};
visitIntAttribute("", (IntValue) -> stringByteArrayLength[0] = IntValue);
尽管我不认为这是最佳实践。我宁愿返回一个新的更改值而不是更改它。
推荐阅读
- javascript - 使用 javascript 处理所需的按钮复选框
- java - 是否可以更改 Liquibase 中变更集之间的数据库连接?
- mongodb-atlas-search - 无法使用 MongoDB Atlas 搜索索引编写任何查询
- python - 我不断收到模块'pandas'没有属性'DataFrame',我无法删除并重新安装pandas包
- android - 带有 DatePicker 的 AlertDialog 使用 Android Studio 进入 Fragment
- python - 如何理解 OpenCV-Python 中的 max() 函数
- java - 使用java删除XML DOM上的特定节点
- angular - 我可以在没有回调的情况下使用 `trackBy` 吗?
- database - ubuntu 中的直线:hive-jdbc-*-standalone.jar':未找到
- c - fwrite() 写入我期望的数量,而不是我想要的数据