开发者

Is it possible for one class to capture information from external classes invoking its methods?

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-operation开发者_StackOverflow社区s before any external class invokes Class A's methods.


Cleanest way is to just pass the caller itself or at least some hints as constructor or method argument.

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

Nasty way is to decipher it based on the stacktrace.

public void doSomething() {
    StackTraceElement caller = Thread.currentThread().getStackTrace()[2];
    String callerClassName = caller.getClassName();
    // ...
}


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.


In addition to constructors, you could use static initialization blocks or initialization blocks.

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!");
   }
}

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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜