![](/img/trans.png)
[英]Java how to access the property of instance of another class in the instance of outer class?
[英]How to Access a Property of the Outer Class Instance from an Inner Class
在自定義類視圖的方法中:
public class View {
private Timer timer;
...
private double[][] allLevels;
...
我有一個帶有抽象調用的方法,該方法需要指向變量allLevels。 該變量是由另一個類GameLogic產生的,但是在應用程序的Main中。 在Main中,來自公共方法的return參數然后傳遞給View:
public class Game extends ApplicationAdapter {
View view;
GameLogic gameLogic;
@Override
public void create () {
System.out.println("Creating");
this.gameLogic = new GameLogic();
this.gameLogic.prepareStimulus();
}
@Override
public void render () {
Gdx.gl.glClearColor(0.5f, 0.5f, 0.5f, 1);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
this.view = new View();
this.view.presentStimulus(this.gameLogic.allLevels);
}
}
由於游戲/業務邏輯非常復雜,我想我會嘗試以MVC式的模式盡可能地分離和封裝。 Main使用libgdx,它要求創建和渲染分開。
我的主要問題是,我無法從對類范圍的抽象調用中訪問類View中的變量。
public void presentStimulus(double[][] allLevels){
...
timer = new Timer();
...
timer.scheduleTask(new Task(){
@Override
public void run(){
DO SOMETHING WITH that.allLevels[0][0]
}
}, .....);
我看過類似的問題 ,但我想我的問題更基本。
IDE無法使用關鍵字“ this”自動完成對屬性的引用。 如何使Run()方法訪問外部類實例的屬性?
問題出在這里(我相當懷疑)-
public void presentStimulus(double[][] allLevels){
...
timer = new Timer();
...
timer.scheduleTask(new Task(){
@Override
public void run(){
DO SOMETHING WITH that.allLevels[0][0]
}
}, .....);
您會看到,在這段代碼time.scheduleTask
,您只是在創建一個new Task
而不執行它。 它在一段時間后與我認為的另一個線程一起執行,因此在不同的上下文中運行,該上下文在執行時沒有allLevels
值。 因此,除非使用closure
否則allLevels
在該run
方法中訪問allLevels
。 我不確定java
是否支持閉包,但是這是一個可能對您有所幫助的類似答案-Java 7中的閉包
您可以使用其他一些解決方案,例如將哈希和allLevels保存在單獨的靜態字典中,該字典可以全局訪問,然后從那里選擇值。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.