如何从匿名内部 class 更改外部变量?
How to change outer variable from anonymous inner class?
我的外部方法中有一个局部变量,我想从匿名内部方法更改它 class。我该怎么做?
我尝试了使用 here
中描述的单元素数组的解决方案
public class outerClass{
static public void outerMethod(Interface interface) {
final String[] variable = new String[1];
new Thread(new Runnable() {
@Override
public void run() {
variable[0] = "Hello";
Log.i("test", variable[0]); // Works, prints "Hello"
}
}).start();
Log.i("test", variable[0]); // Doesn't work, null string
}
}
以及使用描述的支架的解决方案here
public class outerClass{
static public void outerMethod(Interface interface) {
final Holder<String> variable = new Holder<String>;
new Thread(new Runnable() {
@Override
public void run() {
variable.held = "Hello";
Log.i("test", variable.held); // Works, prints "Hello"
}
}).start();
Log.i("test", variable.held); // Doesn't work, null string
}
}
class Holder<String> {
public String held;
}
但出于某种原因,两者都不适用于我的情况。
这可能是相关的,但不同的是我的外部方法是静态的。我还在这里简化了我的代码,原始代码是用于 Android.
上 Retrofit 库的匿名回调 class
您正在创建一个 Runnable class,但它实际上从来没有 运行。您需要通过调用它的 start() 方法来 "start" 它。
但您还必须记住,当您在 outerMethod() 中启动它时,它可能不会 运行 在调用 Log 方法之前(因为它将 运行 在一个单独的线程)和调用代码的顺序不再有保证。
检查线程的同步。使用 Object.wait() 或同步关键字。您的主线程不会等到新创建的线程初始化变量。它应该等待它完成。
顺便说一句,你的 class 不可能是内在的 class。参见 here
我的外部方法中有一个局部变量,我想从匿名内部方法更改它 class。我该怎么做?
我尝试了使用 here
中描述的单元素数组的解决方案public class outerClass{
static public void outerMethod(Interface interface) {
final String[] variable = new String[1];
new Thread(new Runnable() {
@Override
public void run() {
variable[0] = "Hello";
Log.i("test", variable[0]); // Works, prints "Hello"
}
}).start();
Log.i("test", variable[0]); // Doesn't work, null string
}
}
以及使用描述的支架的解决方案here
public class outerClass{
static public void outerMethod(Interface interface) {
final Holder<String> variable = new Holder<String>;
new Thread(new Runnable() {
@Override
public void run() {
variable.held = "Hello";
Log.i("test", variable.held); // Works, prints "Hello"
}
}).start();
Log.i("test", variable.held); // Doesn't work, null string
}
}
class Holder<String> {
public String held;
}
但出于某种原因,两者都不适用于我的情况。
这可能是相关的,但不同的是我的外部方法是静态的。我还在这里简化了我的代码,原始代码是用于 Android.
上 Retrofit 库的匿名回调 class您正在创建一个 Runnable class,但它实际上从来没有 运行。您需要通过调用它的 start() 方法来 "start" 它。
但您还必须记住,当您在 outerMethod() 中启动它时,它可能不会 运行 在调用 Log 方法之前(因为它将 运行 在一个单独的线程)和调用代码的顺序不再有保证。
检查线程的同步。使用 Object.wait() 或同步关键字。您的主线程不会等到新创建的线程初始化变量。它应该等待它完成。
顺便说一句,你的 class 不可能是内在的 class。参见 here