在类的构造函数中找出实例化对象
我如何从java中的构造函数中获取实例化对象?
我想存储对某些 GUI 类的父对象的引用,以模拟事件冒泡 - 调用父处理程序 - 但我不想更改所有现有代码。
How can i get hold of the instantiating object from a constructor in java?
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
简短的回答:在 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.
如果您想知道调用类,请将“this”作为参数传递给构造函数。
编辑:允许重构的现代 IDE 将使这变得非常容易。
If you want to know the invoking class, then pass "this" as a parameter to the constructor.
Edit: A modern IDE allowing refactoring will make this very easy to do.
在不更改大量现有代码的情况下拦截方法调用(包括构造函数)是一回事面向方面的编程< /a> 是为了。
首先查看 AspectJ。
使用AspectJ,您可以定义一个“切入点”,指定您想要拦截某个对象或一组对象的构造函数调用(如果需要,使用通配符),并且在拦截代码(“建议”)中,您将得到方法上下文,其中包括有关调用方法和对象的信息。
您甚至可以使用 AspectJ 将字段添加到对象中以存储父引用,而无需修改其现有代码(这称为“引入”)。
Intercepting method calls (including constructors) without changing a ton of existing code is one thing Aspect-oriented programming was made for.
Check out AspectJ for a start.
With AspectJ, you can define a "pointcut" that specifies that you want to intercept constructor calls for a certain object or set of objects (using wildcards if need be), and within the interception code ("advice"), you will be given method context, which includes information about the both the calling method and object.
You can even use AspectJ to add fields to your object's to store the parent reference without modifying their existing code (this is called "introduction").