一个类是否可以从调用其方法的外部类捕获信息?
如果我们知道某个类(例如 A 类)将被各种类调用,是否可以通过其调用者捕获信息?
我试图在任何外部类调用 A 类的方法之前执行一些前/后操作。
If we know that a certain class say, Class A, will be invoked by a variety of classes, is it possible to capture information by its invokers?
I'm trying to perform some pre-/post-operations before any external class invokes Class A's methods.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
最干净的方法是仅传递调用者本身或至少传递一些提示作为构造函数或方法参数。
令人讨厌的方法是根据堆栈跟踪来破译它。
Cleanest way is to just pass the caller itself or at least some hints as constructor or method argument.
Nasty way is to decipher it based on the stacktrace.
对于一个类来说,了解谁在调用它通常被认为是一个坏主意。它导致设计非常脆弱。也许更好的方法是定义一个任何类都可以遵循的接口,该接口作为方法调用的一部分传入。然后调用方法可以由类 A 执行。将其设为接口意味着 A 不了解调用它的类的具体知识。
另一种选择是在 A 周围使用装饰器。然后装饰器可以实现方法调用,并在对类 A 进行转发调用之前和之后执行操作。
考虑到外部 API,spring 拦截器可能是一个很好的解决方案。
这一切都取决于你想要做什么。但我认为 A 类做这种事情是一个糟糕的设计理念。
It's generally considered a bad idea for a class to have knowledge of who is calling it. It makes for a very brittle design. Perhaps a better one would be define an interface that any class can conform to which is passed in as part of the method call. Then call methods can be executed by class A. Making it an interface means that A doesn't have specific knowledge of the class that is calling it.
Another option is to use a decorator around A. The decorator can then implement the method call and do things pre and post making a forwarding call to class A.
Thinking about external APIs, spring interceptors might be a good solution.
it all comes down to what you are trying to do. But I would suggest that class A doing this sort of thing is a poor design idea.
除了构造函数之外,您还可以使用静态初始化块或初始化块。
我想我误解了你的问题,但我会留下我上面写的内容。
根据您的要求,您还可以查看 AspectJ。它可能会提供一种干净的方式来实现您的目标。
In addition to constructors, you could use static initialization blocks or initialization blocks.
I think I misunderstood your question, but I'll leave what I wrote above.
Depending on your requirements, you could also look at AspectJ. It might offer a clean way to accomplish your goals.