java 基础之--java动态代理

1.抽象角色:声明真实对象与代理对象的共同接口;

2.代理角色:相当于中介的作用,bridge,内部包含对真实角色的reference,在执行真实操作对象时,附加其他操作,相当于对真实角色的封装;

3.真实角色:代理角色所代表的真实对象,也是最终要引用的;

所谓的Dynamic proxy 就是运行时生成的class,在生成它时,你必须给它提供一组interface 对象,那么该class就宣称他实现了该interface,生成它的实例你必须提供一个handler,由它接管实际的工作,让我们看看proxy 的源码:

/**
 * {@code Proxy} provides static methods for creating dynamic proxy
 * classes and instances, and it is also the superclass of all
 * dynamic proxy classes created by those methods.
 
Translation:
  proxy 提供了静态的方法为创建动态代理类和实例,并且它也是所有动态代理类的父类通过这种方式;

 下面是创建的方式:
* <p>To create a proxy for some interface {
@code Foo}:
创建一个代理为一个接口; * <pre> * InvocationHandler handler = new MyInvocationHandler(...); * Class&lt;?&gt; proxyClass = Proxy.getProxyClass(Foo.class.getClassLoader(), Foo.class); * Foo f = (Foo) proxyClass.getConstructor(InvocationHandler.class). * newInstance(handler); * </pre> * or more simply: * <pre> * Foo f = (Foo) Proxy.newProxyInstance(Foo.class.getClassLoader(), * new Class&lt;?&gt;[] { Foo.class }, * handler); * </pre> * * <p>A <i>dynamic proxy class</i> (simply referred to as a <i>proxy * class</i> below) is a class that implements a list of interfaces * specified at runtime when the class is created, with behavior as * described below. *
Translation:

通过源码的实例可以得出来,要实现Java 动态代理必须要提供的是:

java 动态代理是基于接口实现的,所以必须提供一个接口;

1.我们必须提供invocationhandler 所以必须要实现InvocationHandler接口对象,实现invoke 方法,代理的工作就是由它完成的;

2.Java动态代理是一句接口实现的代理类,所以必须提供接口与代理的类;
3.生成代理对象的方法通过Proxy的静态方法:Proxy.newProxyInstance(ClassLoader loader,Class<?>[] interfaceClass, handler);--->handler 即 instance of Invocationhandler

4.通过代理调用方法
package com.java.baseknowledge.proxy;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.ArrayList;
import java.util.List;

public class VectorProxy implements InvocationHandler {

    
    private Object obj;
    public VectorProxy(Object obj) {
        
        this.obj=obj;
    }
    
    public static Object  factory(Object obj) {
        
        
        return Proxy.newProxyInstance(obj.getClass().getClassLoader(), 
                obj.getClass().getInterfaces(), new VectorProxy(obj) );
        
    }
    
    
    
    
    
    
    
    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        // TODO Auto-generated method stub
        System.out.println("before....");
        Object invoke = method.invoke(obj, args);
        for(Object obj:args) {
            
            System.out.println(obj);
        }
        System.out.println("after....");
        
        return invoke;
    }
    
    

    
    public static void main(String[] args) {
        
        List factory = (List)factory(new ArrayList());
        
        factory.add("1");
    }

}
原创打造,多多指教
原文地址:https://www.cnblogs.com/iscys/p/9745381.html