在类的构造函数中找到实例化对象

编程入门 行业动态 更新时间:2024-10-27 00:26:04
本文介绍了在类的构造函数中找到实例化对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

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

更多推荐

在类的构造函数中找到实例化对象

本文发布于:2023-11-04 10:10:27,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1557644.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:函数   实例   对象   中找到

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!