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

find out instantiating object in the constructor of a class(在类的构造函数中找出实例化对象)

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

问题描述

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

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

本文标题为:在类的构造函数中找出实例化对象

基础教程推荐