- public Object getProxy(Object target,Advice advice) {
- this.target = target;
- this.advice = advice;
- return getProxy();
- }
复制代码 你这个方法是不是写错了,再说你这个方法是多余的(这个方法和setAdvice()方法与setTarget()方法重复了),你的这种方案,确实可以达到"在同一个接口里除了可以实现必须要实现的方法之外,还可以在实现必须要实现方法之前与之后做一些其他的事情"的目的.不过你只要在调用createProxy()方法之前,必须要先给ProxyFactory类的target成员与advice成员同时赋上一个实现了Advice接口的类的对象,然后在外部调用createProxy()方法,返回的结果就是实际的代理对象,但是如果要真正成功调用到接口里的方法,必须要将这个所返回的代理对象转型成为Advice接口才可以.以下见具体代码:- import java.lang.reflect.InvocationHandler;
- import java.lang.reflect.Method;
- import java.lang.reflect.Proxy;
- interface Advice {
- void before(Object proxy, Method method, Object[] args);
- void after(Object proxy, Method method, Object[] args);
- void exception(Object proxy, Method method, Object[] args);
- void beforeAndAfter(Object proxy, Method method, Object[] args);
- /**
- * 真正必须要实现的方法
- */
- void print();
- }
- class AdviceImpl implements Advice {
- @Override
- public void before(Object proxy, Method method, Object[] args) {
- System.out.println("before");
- }
- @Override
- public void after(Object proxy, Method method, Object[] args) {
- System.out.println("after");
- }
- @Override
- public void exception(Object proxy, Method method, Object[] args) {
- System.out.println("exception");
- }
- @Override
- public void beforeAndAfter(Object proxy, Method method, Object[] args) {
- System.out.println("beforeAndAfter");
- }
- @Override
- public void print() {
- System.out.println("真正想要实现的方法: print()");
- }
- }
- // 还有一个代理类生成工厂
- class ProxyFactory {
- private Object target;
- private Advice advice;
- public Object createProxy() {
- AdviceImpl adviceImpl = new AdviceImpl();
- getProxy(adviceImpl, adviceImpl);
- Object proxyObj = Proxy.newProxyInstance(target.getClass()
- .getClassLoader(), target.getClass().getInterfaces(),
- new InvocationHandler() {
- @Override
- public Object invoke(Object proxy, Method method,
- Object[] args) throws Throwable {
- Object result = null;
- try {
- advice.beforeAndAfter(proxy, method, args);
- advice.before(proxy, method, args);
- result = method.invoke(target, args);
- advice.after(proxy, method, args);
- advice.beforeAndAfter(proxy, method, args);
- } catch (Exception e) {
- advice.exception(proxy, method, args);
- }
- return result;
- }
- });
- return proxyObj;
- }
- /**
- * 这个方法我给你改一下,就不需要后面的几个方法了.
- *
- * @param target
- * @param advice
- * @return
- */
- public void getProxy(Object target, Advice advice) {
- this.target = target;
- this.advice = advice;
- // return getProxy(this.target, this.advice);
- }
- // public Object getTarget() {
- // return target;
- // }
- //
- // public void setTarget(Object target) {
- // this.target = target;
- // }
- //
- // public Advice getAdvice() {
- // return advice;
- // }
- //
- // public void setAdvice(Advice advice) {
- // this.advice = advice;
- // }
- }
- public class AdviceTest {
- public static void main(String[] args) {
- Advice ai = (Advice) new ProxyFactory().createProxy();
- ai.print();
- }
- }
复制代码 |