0
考慮以下聲明:呼叫變量,但它可能沒有被初始化
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
可能尚未初始化,但它仍然不起作用。
如何才能使這項工作?
一個真實世界的例子將是(從機器人):
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();
上述代碼僅適用於將其實例化爲不在本地範圍內的全局變量。 – 2014-09-01 04:04:54