我想要了解如何將對象設置爲null在java中工作。我有一種情況,似乎乍一看似乎是一個設置爲空的對象突然不是空的,但顯然情況並非如此。在Java中將對象設置爲空和程序流程
我有一個類,我創建一個對象。這個對象是一個場景。這是Open GL ES 2.0項目,因此此場景的render()和updateLogic()方法是從onDrawFrame調用的(這是通過場景管理器控制的,因此我們可以輕鬆切換場景)。
所以,我可能有這樣的事情(代碼上剪下來的問題的目的):
public class MyGLRenderer implements GLSurfaceView.Renderer{
MyScene myScene;
SomeOtherScene someOtherScene;
public void createScenes(){
myScene = new MyScene(this);
someOtherScene = new SomeOtherScene(this);
SceneManager.getInstance().setCurrentScene(myScene);
}
public void cleanUp(){
myScene = null;
Log.v("tag","myScene (from MyGLRenderer) is: "+myScene);
SceneManager.getInstance().setCurrentScene(someOtherScene); //Scene changed but this won't take effect until the next 'tick'
}
@Override
public void onDrawFrame(GL10 gl) {
SceneManager.getInstance().getCurrentScene().updateLogic();
SceneManager.getInstance().getCurrentScene().render();
}
}
在上述情況下,處理上繳myScene這將是這個樣子:
public class MyScene implements Scene{
MyGLRenderer renderer;
public myScene(MyGLRenderer renderer){
this.renderer = renderer;
}
@Override
public void render(){
//Render something here
}
@Override
public void updateLogic(){
doSomething();
//The condition here could be anything - maybe the user taps the sceen and a flag is set in onTouchEvent for example
if (someConditionIsMet){
renderer.cleanup();
}
Log.v("tag","myScene (from within myScene) is: "+this);
}
}
所以,當我設置用我的現場經理現場,處理上繳的那一幕,它的updateLogic和渲染法會從onDrawFrame不斷調用。
當我運行我的代碼時,驚訝地發現它沒有NullpointerException異常。日誌是這樣的:
myScene (from within myScene) is: [email protected]
myScene (from within myScene) is: [email protected]
myScene (from within myScene) is: [email protected]
myScene (from within myScene) is: [email protected]
myScene (from within myScene) is: [email protected]
myScene (from within myScene) is: [email protected]
myScene (from within myScene) is: [email protected]
myScene (from within myScene) is: [email protected]
myScene (from MyGLRenderer) is: null
myScene (from within myScene) is: [email protected]
正如你所看到的,「myScene」是直到清理()方法被調用有效期,並將其設置爲null。但代碼然後返回myScene結束,它仍然有效(不爲空)。
我真的很想了解Java在Java中的工作原理 - 爲什麼它似乎在一分鐘內(或從一個地方)變爲null,然後不是(從不同的地方)?
感謝@StefanHaustein,OK那種有道理。我可能誤解了一些事情。因此,因爲'對象'仍在使用中(它仍然調用render()和updateLogic()方法),所以它不能GC'd,因此它一直保持活動狀態,直到操作系統認爲它是'自由的' - 即使當它被分配給它時的實際引用現在爲null(並且沒有其他實際的'引用'存在,即像this.myScene = myScene在其他某個類中的某處)? – Zippy
我覺得現場經理仍然堅持下去,據此澄清我的回答。 –
Theres仍然是對象的引用,因爲調用堆棧必須從對象上的實例方法返回。另外,正如斯蒂芬所說,對象是零,渲染器的參考是。 –