简体   繁体   中英

Executing a method, when any other method in that class is called other then Aspect

I am looking for java implementation where a method gets executed , when any other method in that class is called other then Aspect (Something like what @before does for Junits)

I prefer not using JAspect. (Just because i dont want to have a Spring config file, if its possible without a Spring XML config )

Simple Example

public class Reader {

    private void init(){}

    private void method1(){}

    private void method2(){}

}

Here every time method1 or method2 is called , it has to call init().

  1. I am not interested to call init() inside that method.
  2. I am not interested to use Aspect with XML config.

Thanks in advance

You can try to adapt your implementation using Javassist . You can find a good introduction here . The following code snippet is taken from the tutorial (slightly adapted) and shows how you can manipulate the bytecode to insert additional commands:

public class Hello {
    public void say() {
        System.out.println("Hello");
    }

    public void ask() {
        System.out.println("HM?");
    }
}

public class Test {
    public static void main(String[] args) throws Exception {
        ClassPool cp = ClassPool.getDefault();
        CtClass cc = cp.get("Hello");
        CtMethod m = cc.getDeclaredMethod("say");
        m.insertBefore("{ ask(); }");
        Class c = cc.toClass();
        Hello h = (Hello)c.newInstance();
        h.say();
    }
}

You should have a look at the Proxy-Pattern.

JAVA already provides this mechanism. It is called dynamic proxy.

Check out this: http://tutorials.jenkov.com/java-reflection/dynamic-proxies.html

Or search for "JAVA dynamic proxies". You will find tons of resources.

Some theory: There are three possibilities to do as you wish:

  1. Aspect orientation (you do not want to)
  2. Template method-Pattern (you do not want to)
  3. Proxy pattern (the only one left)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM