简体   繁体   English

如何从匿名内部类更改外部变量?

[英]How to change outer variable from anonymous inner class?

I have a local variable in my outer method that I want to change from an anonymous inner class. 我在我的外部方法中有一个局部变量,我想从一个匿名内部类更改。 How can I do it? 我该怎么做?

I tried the solution using a one element array described 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
    }
}

and the solution using a holder described 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;
}

but both don't work in my case for some reason. 但由于某些原因,两者都不适用于我的情况。

It might be relevant, but what is different is that my outer method is static. 它可能是相关的,但不同的是我的外部方法是静态的。 I also simplified my code here, the original code was for an anonymous Callback class from the Retrofit library on Android. 我还在这里简化了我的代码,原始代码是来自Android上的Retrofit库的匿名Callback类。

You're creating a Runnable class, but it actually never runs. 您正在创建一个Runnable类,但实际上它从未运行过。 You need to "start" it, by calling its start() method. 你需要通过调用它的start()方法来“启动”它。

But you must also keep in mind, that when you start it inside the outerMethod(), it may not run before the Log method is called (since it will run in a separate thread) and the order in which the code is called is not guaranteed anymore. 但是你还必须记住,当你在outerMethod()中启动它时,它可能不会在调用Log方法之前运行(因为它将在一个单独的线程中运行)并且调用代码的顺序不是保证了。

Check synchronisation of your threads. 检查线程的同步。 Use Object.wait() or synchronized keyword. 使用Object.wait()或synchronized关键字。 Your main thread does not wait until new created thread initializes variable. 您的主线程不会等到新创建的线程初始化变量。 It should wait for this to finish. 它应该等待这个完成。

And by the way your class could not be inner class. 顺便说一句,你的班级不能成为内心阶级。 See here 看到这里

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM