一个类是否可以从调用其方法的外部类中捕获信息?

如果我们知道某个类说A类会被各种类调用,是否有可能通过其调用者捕获信息? 我试图在任何外部类调用A类方法之前执行一些前/后操作。     
已邀请:
最干净的方法是只传递调用者本身或至少一些提示作为构造函数或方法参数。
Other other = new Other(this);
// or
other.doSomething(this);
讨厌的方法是根据堆栈跟踪来解密它。
public void doSomething() {
    StackTraceElement caller = Thread.currentThread().getStackTrace()[2];
    String callerClassName = caller.getClassName();
    // ...
}
    
对于一个班级来说,知道谁在调用它通常被认为是一个坏主意。这使得设计非常脆弱。也许更好的方法是定义一个接口,任何类都可以遵循该接口作为方法调用的一部分传入。然后调用方法可以由类A执行。使它成为一个接口意味着A不具有调用它的类的特定知识。 另一个选择是在A周围使用一个装饰器。装饰器然后可以实现方法调用并在向A类转发调用之前和之后做事。 考虑外部API,弹簧拦截器可能是一个很好的解决方案。 这一切都归结为你想要做的事情。但我认为A类做这种事情是一个糟糕的设计理念。     
除了构造函数之外,您还可以使用静态初始化块或初始化块。
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。它可能提供一种干净的方式来实现您的目标。     

要回复问题请先登录注册