package com.jiaoyiping.util.demo;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * Created with IntelliJ IDEA.
 * User: 焦一平
 * Date: 2015/7/8
 * Time: 10:54
 * To change this template use File | Settings | File Templates.
 * JDK动态代理示例
 */
public class JDKDynamicProxyDemo {
    public static void main(String[] args) {
        Business business = new BusinessImpl();
        Business proxy = (Business)Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(), new Class[]{Business.class}, new BusinessProxy(business));
        proxy.doBusiness();
    }
}

interface Business {
    void doBusiness();
}

class BusinessImpl implements Business {

    @Override
    public void doBusiness() {
        System.out.println("执行业务方法");
    }
}

class BusinessProxy implements InvocationHandler {
    private Business business;

    public BusinessProxy(Business business) {
        this.business = business;
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        System.out.println("before invoke");
        Object result = method.invoke(business, args);
        System.out.println("after invoke");
        return result;
    }
}

 

相关文章:

  • 2021-08-27
  • 2019-02-26
  • 2022-01-20
  • 2023-02-07
  • 2021-06-29
  • 2022-01-14
  • 2020-01-09
  • 2021-12-11
猜你喜欢
  • 2021-07-27
  • 2022-12-23
  • 2021-11-22
  • 2021-05-29
  • 2021-07-14
  • 2022-12-23
  • 2021-07-05
相关资源
相似解决方案