2014-09-01 60 views
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(); 
+0

上述代碼僅適用於將其實例化爲不在本地範圍內的全局變量。 – 2014-09-01 04:04:54

回答

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例如,在致電connect之後撥打scanFile可能會更有意義,並使用符合acc的scanFile方法回叫一個MediaScannerConnection.OnScanCompletedListener回調。

相關問題