問題描述
如何從 java 的構造函數中獲取實例化對象?
How can i get hold of the instantiating object from a constructor in java?
我想為某些 GUI 類存儲對父對象的引用以模擬事件冒泡 - 調用父處理程序 - 但我不想更改所有現有代碼.
I want to store reference to the parent object for some GUI classes to simulate event bubbling - calling parents handlers - but i dont wanna change all the existing code.
推薦答案
簡短的回答:在 Java 中沒有辦法做到這一點.(你可以找出哪個班級叫你,但下面的長答案大部分也適用于那里.)
Short answer: there isn't a way to do this in Java. (You can find out what class called you, but the long answer below applies there for the most part as well.)
長答案:根據調用位置而神奇地表現出不同的代碼幾乎總是一個壞主意.這會讓任何必須維護您的代碼的人感到困惑,并且會嚴重損害您的重構能力.例如,假設您意識到實例化對象的兩個位置具有基本相同的邏輯,因此您決定將公共位分解.驚喜!現在代碼的行為有所不同,因為它是從其他地方實例化的.只需添加參數并修復調用者.從長遠來看,它會為您節省時間.
Long answer: Code that magically behaves differently depending on where it's being invoked from is almost always a bad idea. It's confusing to whoever has to maintain your code, and it seriously hurts your ability to refactor. For example, suppose you realize that two of the places instantiating your object have basicaly the same logic, so you decide to factor out the common bits. Surprise! Now the code behaves differently because it's being instantiated from somewhere else. Just add the parameter and fix the callers. It'll save you time in the long run.
這篇關于在類的構造函數中找出實例化對象的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!