从重写方法中调用变量,但它可能尚未初始化

时间:2014-09-01 03:37:53

标签: java android

考虑以下声明:

public final class MyClass {
    public MyClass(AnotherClass var) {
        /* implementation not shown */
    }

    public void invoke() {
        /* implementation not shown */
    }

    /* there may be more methods/properties listed */
}

public class AnotherClass() {
    public AnotherClass() {
        /* implementation not shown */
    }

    public void method() {
        /* implementation not shown */
    }

    /* there may be more methods/properties listed */
}

这两个类的实现可能不会改变。

现在考虑以下代码:

final MyClass myVariable = new MyClass(anotherVariable);

AnotherClass anotherVariable = new AnotherClass() {
    @Override
    public void method() {
        myVariable.invoke();
    }
};

显然它无法运行,因为anotherVariable在第一行没有准备就绪,但是如果我重新排列这两个语句......

AnotherClass anotherVariable = new AnotherClass() {
    @Override
    public void method() {
        myVariable.invoke();
    }
};

final MyClass myVariable = new MyClass(anotherVariable);

然后,myVariable可能尚未初始化,但仍然无效。

我怎么能让这个工作?


真实世界的例子是(来自android):

final MediaScannerConnection msc = new MediaScannerConnection(this,
                new MediaScannerConnection.MediaScannerConnectionClient() {
                    @Override
                    public void onScanCompleted(String path, Uri uri){
                        msc.disconnect();
                    }

                    @Override
                    public void onMediaScannerConnected() {
                        msc.scanFile("", null);
                    }
                });
msc.connect();

1 个答案:

答案 0 :(得分:1)

这是一种方法:

AnotherClass anotherVariable = new AnotherClass() {
    private MyClass myVariable;

    public void setMyVariable(MyClass myVariable) {
        this.myVariable = myVariable;
    }

    @Override
    public void method() {
        this.myVariable.invoke();
    }
};

MyClass myVariable = new MyClass(anotherVariable);
anotherVariable.setMyVariable(myVariable);
anotherVariable.method();

至于您的Android示例,调用scanFile后调用connect可能更有意义,并使用接受scanFile回调的MediaScannerConnection.OnScanCompletedListener方法。< / p>