接口类:

public interface Service {
   public void print();
}

实现类

package com.tao.proxy;
public class ServiceImpl implements Service {
    @Override
 public void print() {
        System.out.println("hello");
 }
}

代理类

public class TaoInvoker implements InvocationHandler {
    private Object object ;
 public TaoInvoker() {
    }
    public TaoInvoker(Object object) {
        this.object = object;
 }
    public Object newProxy(Object target){
        this.object = target;
 return Proxy.newProxyInstance(target.getClass().getClassLoader(),target.getClass().getInterfaces(),this);
 }
    @Override
 public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        System.out.println("增强代码");
 return method.invoke(object, args);
 }
    public static void main(String[] args) {
        Service service = new ServiceImpl();
 Service o = (Service) new TaoInvoker().newProxy(new ServiceImpl());
 o.print();
 }
}
增强代码
hello

林慫慫
11 声望0 粉丝

引用和评论

0 条评论