問(wèn)題描述
如何從 java 的構(gòu)造函數(shù)中獲取實(shí)例化對(duì)象?
How can i get hold of the instantiating object from a constructor in java?
我想為某些 GUI 類存儲(chǔ)對(duì)父對(duì)象的引用以模擬事件冒泡 - 調(diào)用父處理程序 - 但我不想更改所有現(xiàn)有代碼.
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.
推薦答案
簡(jiǎn)短的回答:在 Java 中沒(méi)有辦法做到這一點(diǎn).(你可以找出哪個(gè)班級(jí)叫你,但下面的長(zhǎng)答案大部分也適用于那里.)
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.)
長(zhǎng)答案:根據(jù)調(diào)用位置而神奇地表現(xiàn)出不同的代碼幾乎總是一個(gè)壞主意.這會(huì)讓任何必須維護(hù)您的代碼的人感到困惑,并且會(huì)嚴(yán)重?fù)p害您的重構(gòu)能力.例如,假設(shè)您意識(shí)到實(shí)例化對(duì)象的兩個(gè)位置具有基本相同的邏輯,因此您決定將公共位分解.驚喜!現(xiàn)在代碼的行為有所不同,因?yàn)樗菑钠渌胤綄?shí)例化的.只需添加參數(shù)并修復(fù)調(diào)用者.從長(zhǎng)遠(yuǎn)來(lái)看,它會(huì)為您節(jié)省時(shí)間.
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.
這篇關(guān)于在類的構(gòu)造函數(shù)中找出實(shí)例化對(duì)象的文章就介紹到這了,希望我們推薦的答案對(duì)大家有所幫助,也希望大家多多支持html5模板網(wǎng)!