简单的自己创建代理对象

1.获取目标对象
2.在基于jdk方式下:
invocationHandler接口(创建代理实例对象的接口)
创建一个代理对象使用newProxyInstance方法
源码:

@CallerSensitive
public static Object newProxyInstance(ClassLoader loader,
                                      Class[] interfaces,
                                      InvocationHandler h)
    throws IllegalArgumentException
{
    Objects.requireNonNull(h);
    final Class[] intfs = interfaces.clone();
    final SecurityManager sm = System.getSecurityManager();
    if (sm != null) {
        checkProxyAccess(Reflection.getCallerClass(), loader, intfs);
    }

需要三个参数:
2.1目标类的类加载器
2.2目标类对象实现的接口
2.3为代理对象处理业务的对象
实例:

package com.cy.jdkproxy;
import com.cy.pj.sys.service.SysLogService;
import com.cy.pj.sys.service.serviceImpl.SysLogServiceImpl;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
//简单的收到创建代理
public class JDKProxyTests {
    public static void main(String[] args) {
        //获取目标对象
 SysLogService  sysLogService=new SysLogServiceImpl();
        //2.基于jdk方式
 //2.1获取类加载器
 ClassLoader classLoader=sysLogService.getClass().getClassLoader();
        //2.2获取目标对象实现的接口
 Class[] interfaces =sysLogService.getClass().getInterfaces();
        //2.3创建IncovationHandler(为代理对象处理业务的对象)
 class ProxyHandler implements InvocationHandler{
            private Object targetObj;
            public ProxyHandler(Object targetObj){
                this.targetObj=targetObj;
            }
            @Override
 public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                //在此方法中如何调用目标对象的方法(反射):目标对象,方法,参数
 Object result=method.invoke(targetObj, args);
                return result;
            }
        }
        SysLogService proxy= (SysLogService) Proxy.newProxyInstance
 (classLoader,interfaces,new ProxyHandler(sysLogService));
        System.out.println(proxy.getClass().getName());
        proxy.deleteById(11L,12L);
    }
}

业务层接口:

package com.cy.api.proxy;
public interface NoticeService {
      int deleteById(Long ...id);
}

业务层接口的实现类:

package com.cy.api.proxy;
import java.util.Arrays;
public class NoticeServiceImpl implements NoticeService{
    @Override
    public int deleteById(Long... id) {
        System.out.println("delete "+Arrays.toString(id));
        return id.length;
    }
}

你可能感兴趣的:(java)