AspectJ constructor force factory pattern

Deadly 提交于 2019-12-04 16:39:38

If I understand you right you could do the following:

I've created three packages:

  • aspectj for the aspect and AWrapped.java
  • unknown for A.java (could also be Bytecode but then you have to use Load Time Weaving)
  • main to test A a = new A();

MyAspect to return the AWrapped object if a new() call is made on class A:

package aspectj;

import unknown.A;

@Aspect
public class MyAspect {

    @Pointcut("call(unknown.A.new(..)) && !within(aspectj..*)")
    public static void init(ProceedingJoinPoint pjp) {
    }

    @Around("init(pjp)")
    public Object initAdvice(ProceedingJoinPoint pjp) throws Throwable{
        Object ret = pjp.proceed();
        return new AWrapped((A) ret);
        }

}

For testing:

package main;

import unknown.A;

public class Main {

    public static void main(String[] args) {
        A a = new A();
        System.out.println(a.sayHello());
    }
}

This outputs:

gday mate
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!