AspectJ构造函数强制工厂模式 [英] AspectJ constructor force factory pattern
问题描述
我想将对象返回从调用更改为构造函数
I want to change the object return from call to a constuctor
FROM
public class A {
public A(){
}
public String sayHello() {
return "hello";
}
public String foo() {
return "foo";
}
}
TO
public class AWrapped extends A {
private A wrapped;
public AWrapped() {
super();
}
public AWrapped(A pWrapped) {
wrapped=pWrapped;
}
public String foo() {
return wrapped.foo();
}
public String sayHello {
return "gday mate";
}
}
我想做的是更改从通话中返回的对象
What i want to do is to change the object that is returned from a call
A a = new A();
a.sayHello() returns "gday mate"
a是AWrapped的实例
a is an instaceof AWrapped
我知道这通常是通过工厂模式完成的,但我无法访问A的代码或创建新A的代码。并且有1000个地方可以创建A.
I understand that this would usually be done with a factory pattern but I dont have access to the code of A or the code that makes new A's. And there are 1000s of places that A can be created.
似乎Aspectj可能会做到这一点,但我不太了解它,如果AspectJ会做的伎俩如何绕过无限包装我需要知道它是从内部和方面构建的,所以它不会再次包裹它。
It seems that Aspectj might do the trick, but i dont know much about it, If AspectJ would do the trick how to I get around the infinite wrapping i need to know that its being consturcted from within and aspect so it doesnt wrapp it again.
感谢您的帮助
Jon
Thanks for the help Jon
推荐答案
如果我理解你,你可以做以下事情:
If I understand you right you could do the following:
我创建了三个包:
- 方面的aspectj和AWrapped.java
- 未知的A.java(可能也是Bytecode,但你必须使用加载时间编织)
- 主要测试
A a =新A();
- 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如果<$ c $,则返回AWrapped对象c> 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);
}
}
进行测试:
package main;
import unknown.A;
public class Main {
public static void main(String[] args) {
A a = new A();
System.out.println(a.sayHello());
}
}
此输出:
gday mate
这篇关于AspectJ构造函数强制工厂模式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!