在类的构造函数中找到实例化对象 [英] find out instantiating object in the constructor of a class

查看:189
本文介绍了在类的构造函数中找到实例化对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我如何从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.

这篇关于在类的构造函数中找到实例化对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆