1

如果我们知道某个类,比如 Class A,将被各种类调用,是否有可能通过它的调用者捕获信息?

我试图在任何外部类调用 A 类的方法之前执行一些前/后操作。

4

3 回答 3

3

通常认为一个类知道谁在调用它是一个坏主意。它使设计非常脆弱。也许更好的方法是定义一个任何类都可以遵循的接口,该接口作为方法调用的一部分传入。然后调用方法可以由类 A 执行。使其成为接口意味着 A 不知道调用它的类的具体知识。

另一种选择是在 A 周围使用装饰器。装饰器然后可以实现方法调用并在对类 A 进行转发调用之前和之后执行操作。

考虑到外部 API,spring 拦截器可能是一个很好的解决方案。

这一切都归结为您正在尝试做的事情。但我会建议 A 类做这种事情是一个糟糕的设计理念。

于 2011-01-21T02:37:37.283 回答
3

最简洁的方法是仅将调用者本身或至少一些提示作为构造函数或方法参数传递。

Other other = new Other(this);
// or
other.doSomething(this);

讨厌的方法是根据堆栈跟踪对其进行解密。

public void doSomething() {
    StackTraceElement caller = Thread.currentThread().getStackTrace()[2];
    String callerClassName = caller.getClassName();
    // ...
}
于 2011-01-21T02:22:51.923 回答
0

除了构造函数之外,您还可以使用静态初始化块或初始化块。

class A
{

   private Object a;

   {
      // Arbitrary code executed each time an instance of A is created.
      System.out.println("Hey, I'm a brand new object!");
      System.out.println("I get called independently of any constructor call.");
   }

   static
   {
      // Arbitrary *static* code
      System.out.println("Some static initialization code just got executed!");
   }

   public A()
   {
      // Plain-Jane constructor
      System.out.println("You're probably familiar with me already!");
   }
}

我想我误解了你的问题,但我会留下我上面写的。

根据您的要求,您还可以查看AspectJ。它可能会提供一种干净的方式来实现您的目标。

于 2011-01-21T02:23:51.810 回答