gpt4 book ai didi

java - 绕过 'Cannot refer to a non-final variable inside an inner class defined'

转载 作者:行者123 更新时间:2023-11-29 03:35:21 24 4
gpt4 key购买 nike

我有以下代码,但是当我在新的 Thread 类之外声明 String 行时,我得到了一个异常。我来自 C# 背景,所以我现在明白 Java 不支持真正的闭包。所以我的问题是:

如何在新线程之外声明一个字符串并在新线程中使用它?

Cannot refer to a non-final variable line inside an inner class defined in a different method

ProcessBuilder builder =
new ProcessBuilder("/Users/Joe/Desktop/file", "-i", src);
builder.redirectErrorStream(true);
Process process = builder.start();
final InputStream is = process.getInputStream();
String line;
new Thread(new Runnable() {
@Override public void run() {
try {
BufferedReader br = new BufferedReader(new InputStreamReader(is));
while ((br.readLine()) != null) {
line += br.readLine() + "\n";
}
} catch (IOException e) {
e.printStackTrace();
}
}
}).start();

最佳答案

line 更改为 StringBuilder 并将其声明为 final。然后更改 run() 方法以附加到 StringBuilder

假设您在尝试读取主线程中的之前join()子线程,则不需要使用StringBuffer.

关于java - 绕过 'Cannot refer to a non-final variable inside an inner class defined',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15864109/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com