java proxy

之前知道使用 JDK Proxy 和 Cglib 生成動態代理類。可是每次被問到,這二者的區別,性能比較等問題的時候,老是答不出來。其實仍是對這兩個底層實現不夠了解。html

1、動態代理的使用

先來講一下 java 自帶的 動態代理。JDK的代理咱們用到的就是兩個類 Proxy 和 InvocationHandlerjava

public interface FooBarService {

	int getOrder();
}
public class FooBarServiceImpl implements FooBarService{

	@Override
	public int getOrder() {
		System.out.println("真正的業務調用");
		return 1;
	}
}

 

package lujing.sample.core.proxy;

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

public class FooBarServiceProxy implements InvocationHandler{

	private FooBarService target = null;
	
	public FooBarServiceProxy(FooBarService fooBarService){
		target = fooBarService;
	}
	
	@Override
	public Object invoke(Object proxy, Method method, Object[] args)
			throws Throwable {
		System.out.println("其實我是個代理");
		return method.invoke(target, args);
	}
	
	public FooBarService getProxy(){
		return (FooBarService)Proxy.newProxyInstance(FooBarServiceProxy.class.getClassLoader(), new Class[]{FooBarService.class}, this);
	}
}

運行輸出:apache

public class Launcher {
	public static void main(String[] args) {
		FooBarServiceProxy proxy = new FooBarServiceProxy(new FooBarServiceImpl());
		FooBarService service = proxy.getProxy();
		System.out.println(service.getClass().getName());
		System.out.println(service.getOrder());
	}
}
com.sun.proxy.$Proxy0
其實我是個代理
真正的業務調用
1

2、動態代理源碼分析

@CallerSensitive
    public static Object newProxyInstance(ClassLoader loader,
                                          Class<?>[] interfaces,
                                          InvocationHandler h)
        throws IllegalArgumentException
    {
        if (h == null) {
            throw new NullPointerException();
        }

        final Class<?>[] intfs = interfaces.clone();
        final SecurityManager sm = System.getSecurityManager();
        if (sm != null) {
            checkProxyAccess(Reflection.getCallerClass(), loader, intfs);
        }

        /*
         *  生成代理類
         */
        Class<?> cl = getProxyClass0(loader, intfs);

        /*
         * Invoke its constructor with the designated invocation handler.
         */
        try {
            // 獲取構造方法
            // private static final Class<?>[] constructorParams =
            // { InvocationHandler.class };
            final Constructor<?> cons = cl.getConstructor(constructorParams);
            final InvocationHandler ih = h;
            if (sm != null && ProxyAccessHelper.needsNewInstanceCheck(cl)) {
                // create proxy instance with doPrivilege as the proxy class may
                // implement non-public interfaces that requires a special permission
                return AccessController.doPrivileged(new PrivilegedAction<Object>() {
                    // 實例化
                    public Object run() {
                        return newInstance(cons, ih);
                    }
                });
            } else {
                // 實例化
                return newInstance(cons, ih);
            }
        } catch (NoSuchMethodException e) {
            throw new InternalError(e.toString());
        }
    }

從上面代碼看出大概作了3步:緩存

1. 生成了一個新的代理 Class app

2. 獲取代理類的構造函數。這個代理Class的構造函數,須要傳一個 InvocationHandler,這個InvocationHandler就是咱們須要本身實現的接口。maven

3. 根據構造函數實例化一個代理類ide

這3步的核心就是生成代理類Class函數

/**
     * 生成代理Class
     */
    private static Class<?> getProxyClass0(ClassLoader loader,
                                           Class<?>... interfaces) {
        if (interfaces.length > 65535) {
            throw new IllegalArgumentException("interface limit exceeded");
        }

        // 若是須要的代理Class已經建立過,就直接使用緩存
        // 不然 , 經過 ProxyClassFactory 建立代理類
        return proxyClassCache.get(loader, interfaces);
    }

proxyClassCache.get 的處理正如上面說到的:源碼分析

1. 若是須要的代理Class已經建立過,就直接使用緩存
2. 不然 , 經過 ProxyClassFactory 建立代理類性能

public V get(K key, P parameter) {
        Objects.requireNonNull(parameter);

        expungeStaleEntries();

        // 只有被同一個 ClassLoader 加載的類,纔算同一個類。因此這裏Java Proxy 以 ClassLoader
        // 做爲一個Key,分類去緩存
        Object cacheKey = CacheKey.valueOf(key, refQueue);

        // ClassLoader 對應的 代理信息
        ConcurrentMap<Object, Supplier<V>> valuesMap = map.get(cacheKey);
        if (valuesMap == null) {
            // 空的話建立
            ConcurrentMap<Object, Supplier<V>> oldValuesMap
                = map.putIfAbsent(cacheKey,
                                  valuesMap = new ConcurrentHashMap<>());
            if (oldValuesMap != null) {
                valuesMap = oldValuesMap;
            }
        }

        // subKeyFactory.apply 正真的建立 代理 Class
        Object subKey = Objects.requireNonNull(subKeyFactory.apply(key, parameter));
        Supplier<V> supplier = valuesMap.get(subKey);
        Factory factory = null;

        // 處理緩存
        while (true) {
            if (supplier != null) {
                // supplier might be a Factory or a CacheValue<V> instance
                V value = supplier.get();
                if (value != null) {
                    return value;
                }
            }
            // else no supplier in cache
            // or a supplier that returned null (could be a cleared CacheValue
            // or a Factory that wasn't successful in installing the CacheValue)

            // lazily construct a Factory
            if (factory == null) {
                factory = new Factory(key, parameter, subKey, valuesMap);
            }

            if (supplier == null) {
                supplier = valuesMap.putIfAbsent(subKey, factory);
                if (supplier == null) {
                    // successfully installed Factory
                    supplier = factory;
                }
                // else retry with winning supplier
            } else {
                if (valuesMap.replace(subKey, supplier, factory)) {
                    // successfully replaced
                    // cleared CacheEntry / unsuccessful Factory
                    // with our Factory
                    supplier = factory;
                } else {
                    // retry with current supplier
                    supplier = valuesMap.get(subKey);
                }
            }
        }
    }
@Override
        public Class<?> apply(ClassLoader loader, Class<?>[] interfaces) {

            Map<Class<?>, Boolean> interfaceSet = new IdentityHashMap<>(interfaces.length);
            // 校驗
            for (Class<?> intf : interfaces) {
                /*
                 * Verify that the class loader resolves the name of this
                 * interface to the same Class object.
                 */
                Class<?> interfaceClass = null;
                try {
                    interfaceClass = Class.forName(intf.getName(), false, loader);
                } catch (ClassNotFoundException e) {
                }
                if (interfaceClass != intf) {
                    throw new IllegalArgumentException(
                        intf + " is not visible from class loader");
                }
                /*
                 * Verify that the Class object actually represents an
                 * interface.
                 */
                if (!interfaceClass.isInterface()) {
                    throw new IllegalArgumentException(
                        interfaceClass.getName() + " is not an interface");
                }
                /*
                 * Verify that this interface is not a duplicate.
                 */
                if (interfaceSet.put(interfaceClass, Boolean.TRUE) != null) {
                    throw new IllegalArgumentException(
                        "repeated interface: " + interfaceClass.getName());
                }
            }

            String proxyPkg = null;     // package to define proxy class in

            /*
             * Record the package of a non-public proxy interface so that the
             * proxy class will be defined in the same package.  Verify that
             * all non-public proxy interfaces are in the same package.
             */
            for (Class<?> intf : interfaces) {
                int flags = intf.getModifiers();
                if (!Modifier.isPublic(flags)) {
                    String name = intf.getName();
                    int n = name.lastIndexOf('.');
                    String pkg = ((n == -1) ? "" : name.substring(0, n + 1));
                    if (proxyPkg == null) {
                        proxyPkg = pkg;
                    } else if (!pkg.equals(proxyPkg)) {
                        throw new IllegalArgumentException(
                            "non-public interfaces from different packages");
                    }
                }
            }

            if (proxyPkg == null) {
                // if no non-public proxy interfaces, use com.sun.proxy package
                proxyPkg = ReflectUtil.PROXY_PACKAGE + ".";
            }

            /*
             * 代理類名稱如:com.sun.proxy.$Proxy0
             */
            long num = nextUniqueNumber.getAndIncrement();
            String proxyName = proxyPkg + proxyClassNamePrefix + num;

            /*
             * 生成二進制字節碼
             */
            byte[] proxyClassFile = ProxyGenerator.generateProxyClass(
                proxyName, interfaces);
            try {
                // 二進制轉Class,這裏調的是 native 本地方法
                return defineClass0(loader, proxyName,
                                    proxyClassFile, 0, proxyClassFile.length);
            } catch (ClassFormatError e) {
                /*
                 * A ClassFormatError here means that (barring bugs in the
                 * proxy class generation code) there was some other
                 * invalid aspect of the arguments supplied to the proxy
                 * class creation (such as virtual machine limitations
                 * exceeded).
                 */
                throw new IllegalArgumentException(e.toString());
            }
        }
    }

這裏主要經過 ProxyGenerator.generateProxyClass 生成字節碼數據,ProxyGenerator 沒有源代碼,不過網上查一下仍是有源碼的,這裏參考的是 openJDK的源碼

public static byte[] generateProxyClass(final String name, Class<?>[] interfaces, int accessFlags) {
        ProxyGenerator gen = new ProxyGenerator(name, interfaces, accessFlags);
        //真正生成字節碼的方法
        final byte[] classFile = gen.generateClassFile();
        //若是saveGeneratedFiles爲true 則生成字節碼文件,因此在開始咱們要設置這個參數
        //固然,也能夠經過返回的bytes本身輸出
        if (saveGeneratedFiles) {
            java.security.AccessController.doPrivileged( new java.security.PrivilegedAction<Void>() {
                        public Void run() {
                            try {
                                int i = name.lastIndexOf('.');
                                Path path;
                                if (i > 0) {
                                    Path dir = Paths.get(name.substring(0, i).replace('.', File.separatorChar));
                                    Files.createDirectories(dir);
                                    path = dir.resolve(name.substring(i+1, name.length()) + ".class");
                                } else {
                                    path = Paths.get(name + ".class");
                                }
                                Files.write(path, classFile);
                                return null;
                            } catch (IOException e) {
                                throw new InternalError( "I/O exception saving generated file: " + e);
                            }
                        }
                    });
        }
        return classFile;
    }

核心仍是在 generateClassFile()上

private byte[] generateClassFile() {
        /* ============================================================
         * Step 1: Assemble ProxyMethod objects for all methods to generate proxy dispatching code for.
         * 步驟1:爲全部方法生成代理調度代碼,將代理方法對象集合起來。
         */
        //增長 hashcode、equals、toString方法
        addProxyMethod(hashCodeMethod, Object.class);
        addProxyMethod(equalsMethod, Object.class);
        addProxyMethod(toStringMethod, Object.class);
        //增長接口方法
        for (Class<?> intf : interfaces) {
            for (Method m : intf.getMethods()) {
                addProxyMethod(m, intf);
            }
        }

        /*
         * 驗證方法簽名相同的一組方法,返回值類型是否相同;意思就是重寫方法要方法簽名和返回值同樣
         */
        for (List<ProxyMethod> sigmethods : proxyMethods.values()) {
            checkReturnTypes(sigmethods);
        }

        /* ============================================================
         * Step 2: Assemble FieldInfo and MethodInfo structs for all of fields and methods in the class we are generating.
         * 爲類中的方法生成字段信息和方法信息
         */
        try {
            //增長構造方法
            methods.add(generateConstructor());
            for (List<ProxyMethod> sigmethods : proxyMethods.values()) {
                for (ProxyMethod pm : sigmethods) {
                    // add static field for method's Method object
                    fields.add(new FieldInfo(pm.methodFieldName,
                            "Ljava/lang/reflect/Method;",
                            ACC_PRIVATE | ACC_STATIC));
                    // generate code for proxy method and add it
                    methods.add(pm.generateMethod());
                }
            }
            //增長靜態初始化信息
            methods.add(generateStaticInitializer());
        } catch (IOException e) {
            throw new InternalError("unexpected I/O Exception", e);
        }

        if (methods.size() > 65535) {
            throw new IllegalArgumentException("method limit exceeded");
        }
        if (fields.size() > 65535) {
            throw new IllegalArgumentException("field limit exceeded");
        }

        /* ============================================================
         * Step 3: Write the final class file.
         * 步驟3:編寫最終類文件
         */
        /*
         * Make sure that constant pool indexes are reserved for the following items before starting to write the final class file.
         * 在開始編寫最終類文件以前,確保爲下面的項目保留常量池索引。
         */
        cp.getClass(dotToSlash(className));
        cp.getClass(superclassName);
        for (Class<?> intf: interfaces) {
            cp.getClass(dotToSlash(intf.getName()));
        }

        /*
         * Disallow new constant pool additions beyond this point, since we are about to write the final constant pool table.
         * 設置只讀,在這以前不容許在常量池中增長信息,由於要寫常量池表
         */
        cp.setReadOnly();

        ByteArrayOutputStream bout = new ByteArrayOutputStream();
        DataOutputStream dout = new DataOutputStream(bout);

        // 這裏就是安裝字節碼規範寫 二進制 數據了
        try {
            // u4 magic;
            dout.writeInt(0xCAFEBABE);
            // u2 次要版本;
            dout.writeShort(CLASSFILE_MINOR_VERSION);
            // u2 主版本
            dout.writeShort(CLASSFILE_MAJOR_VERSION);

            cp.write(dout);             // (write constant pool)

            // u2 訪問標識;
            dout.writeShort(accessFlags);
            // u2 本類名;
            dout.writeShort(cp.getClass(dotToSlash(className)));
            // u2 父類名;
            dout.writeShort(cp.getClass(superclassName));
            // u2 接口;
            dout.writeShort(interfaces.length);
            // u2 interfaces[interfaces_count];
            for (Class<?> intf : interfaces) {
                dout.writeShort(cp.getClass(
                        dotToSlash(intf.getName())));
            }
            // u2 字段;
            dout.writeShort(fields.size());
            // field_info fields[fields_count];
            for (FieldInfo f : fields) {
                f.write(dout);
            }
            // u2 方法;
            dout.writeShort(methods.size());
            // method_info methods[methods_count];
            for (MethodInfo m : methods) {
                m.write(dout);
            }
            // u2 類文件屬性:對於代理類來講沒有類文件屬性;
            dout.writeShort(0); // (no ClassFile attributes for proxy classes)

        } catch (IOException e) {
            throw new InternalError("unexpected I/O Exception", e);
        }

        return bout.toByteArray();
    }

這裏咱們很清楚的看到,在建立構造函數的時候,使用了 InvocationHandler 做爲入參:

/**
     * Generate the constructor method for the proxy class.
     */
    private MethodInfo generateConstructor() throws IOException {
        MethodInfo minfo = new MethodInfo(
            "<init>", "(Ljava/lang/reflect/InvocationHandler;)V",
            ACC_PUBLIC);

        DataOutputStream out = new DataOutputStream(minfo.code);

        code_aload(0, out);

        code_aload(1, out);

        out.writeByte(opc_invokespecial);
        out.writeShort(cp.getMethodRef(
            superclassName,
            "<init>", "(Ljava/lang/reflect/InvocationHandler;)V"));

        out.writeByte(opc_return);

        minfo.maxStack = 10;
        minfo.maxLocals = 2;
        minfo.declaredExceptions = new short[0];

        return minfo;
    }

 

/**
     * Add another method to be proxied, either by creating a new
     * ProxyMethod object or augmenting an old one for a duplicate
     * method.
     *
     * "fromClass" indicates the proxy interface that the method was
     * found through, which may be different from (a subinterface of)
     * the method's "declaring class".  Note that the first Method
     * object passed for a given name and descriptor identifies the
     * Method object (and thus the declaring class) that will be
     * passed to the invocation handler's "invoke" method for a given
     * set of duplicate methods.
     */
    private void addProxyMethod(Method m, Class fromClass) {
        String name = m.getName();
        Class[] parameterTypes = m.getParameterTypes();
        Class returnType = m.getReturnType();
        Class[] exceptionTypes = m.getExceptionTypes();

        String sig = name + getParameterDescriptors(parameterTypes);
        List<ProxyMethod> sigmethods = proxyMethods.get(sig);
        if (sigmethods != null) {
            for (ProxyMethod pm : sigmethods) {
                if (returnType == pm.returnType) {
                    /*
                     * Found a match: reduce exception types to the
                     * greatest set of exceptions that can thrown
                     * compatibly with the throws clauses of both
                     * overridden methods.
                     */
                    List<Class> legalExceptions = new ArrayList<Class>();
                    collectCompatibleTypes(
                        exceptionTypes, pm.exceptionTypes, legalExceptions);
                    collectCompatibleTypes(
                        pm.exceptionTypes, exceptionTypes, legalExceptions);
                    pm.exceptionTypes = new Class[legalExceptions.size()];
                    pm.exceptionTypes =
                        legalExceptions.toArray(pm.exceptionTypes);
                    return;
                }
            }
        } else {
            sigmethods = new ArrayList<ProxyMethod>(3);
            proxyMethods.put(sig, sigmethods);
        }
        sigmethods.add(new ProxyMethod(name, parameterTypes, returnType,
                                       exceptionTypes, fromClass));
    }

3、反編譯查看Class 

Java中生成的字節碼是二進制數據,並且不像咱們以前能夠直接拿到.class文件。那這個怎麼導出呢?

這個時候,Java代理機制就起做用了。

2.1 定義代理入口

public class Launcher {

	/**
	 * Java 代理入口
	 * @param agentArgs
	 * @param inst
	 */
	public static void premain(String agentArgs, Instrumentation inst) {
        inst.addTransformer(new ClassTransformer());
    }
}

 2.2 導出字節碼處理

public class ClassTransformer implements ClassFileTransformer{

	/**
	 * JDK 生成的代理的命名: com.sun.proxy.$Proxy0
	 */
	private static final String PROXY_PREFIX = "com/sun/proxy/$Proxy";
	
	private String DEFAULT_FILE_PATH = "F://proxy.class";
	
	private String filePath = DEFAULT_FILE_PATH;
	
	@Override
	public byte[] transform(ClassLoader loader, String className,
			Class<?> classBeingRedefined, ProtectionDomain protectionDomain,
			byte[] classfileBuffer) throws IllegalClassFormatException {
		
		if(shouldExport(loader, className, classBeingRedefined)){
			doExportClass(loader, className, classBeingRedefined, protectionDomain, classfileBuffer);
		}
		return classfileBuffer;
	}

	/**
	 * 導出Class文件
	 * @param loader
	 * @param className
	 * @param classBeingRedefined
	 * @param protectionDomain
	 * @param classfileBuffer
	 */
	private void doExportClass(ClassLoader loader, String className,
			Class<?> classBeingRedefined, ProtectionDomain protectionDomain,
			byte[] classfileBuffer) {
		try {
			FileOutputStream fos;
			File file = new File(filePath);
			if(file.exists()){
				file.createNewFile();
			}
			fos = new FileOutputStream(file);
	        fos.write(classfileBuffer);
	        fos.close(); 
	        System.out.println("嘗試將" + className + "寫入到文件" + filePath + "成功");
		} catch (Exception e) {
			System.out.println("嘗試將" + className + "寫入到文件" + filePath + "失敗");
		}

	}

	/**
	 * 是否須要導出
	 * @param loader
	 * @param className
	 * @param classBeingRedefined
	 * @return
	 */
	private boolean shouldExport(ClassLoader loader, String className,
			Class<?> classBeingRedefined) {
		return className.startsWith(PROXY_PREFIX);
	}
}

2.3 maven打包參數,最主要是Premain-Class 

<build>
		<finalName>agent</finalName>
		<plugins>
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-jar-plugin</artifactId>
				<configuration>
					<archive>
						<manifestEntries>
							<Premain-Class>
								me.kimi.instrument.Launcher
							</Premain-Class>
						</manifestEntries>
					</archive>
				</configuration>
			</plugin>
		</plugins>
	</build>

clean package 就導出一個 agent.jar啦

而後run configuration  加入代理jar:

運行一下代理類就導出到 proxy.class文件了。而後找一個反編譯軟件(個人是jad):

// Decompiled by Jad v1.5.8g. Copyright 2001 Pavel Kouznetsov.
// Jad home page: http://www.kpdus.com/jad.html
// Decompiler options: packimports(3) 

package com.sun.proxy;

import java.lang.reflect.*;
import lujing.sample.core.proxy.FooBarService;

public final class $Proxy0 extends Proxy
    implements FooBarService
{
    
    // 構造函數,接受 InvocationHandler 參數
    public $Proxy0(InvocationHandler invocationhandler)
    {
        super(invocationhandler);
    }

    public final boolean equals(Object obj)
    {
        try
        {
            return ((Boolean)super.h.invoke(this, m1, new Object[] {
                obj
            })).booleanValue();
        }
        catch(Error _ex) { }
        catch(Throwable throwable)
        {
            throw new UndeclaredThrowableException(throwable);
        }
    }

    public final int hashCode()
    {
        try
        {
            return ((Integer)super.h.invoke(this, m0, null)).intValue();
        }
        catch(Error _ex) { }
        catch(Throwable throwable)
        {
            throw new UndeclaredThrowableException(throwable);
        }
    }

    public final int getOrder()
    {
        try
        {
            return ((Integer)super.h.invoke(this, m3, null)).intValue();
        }
        catch(Error _ex) { }
        catch(Throwable throwable)
        {
            throw new UndeclaredThrowableException(throwable);
        }
    }

    public final String toString()
    {
        try
        {
            return (String)super.h.invoke(this, m2, null);
        }
        catch(Error _ex) { }
        catch(Throwable throwable)
        {
            throw new UndeclaredThrowableException(throwable);
        }
    }

    private static Method m1;
    private static Method m0;
    private static Method m3;
    private static Method m2;

    static 
    {
        try
        {
            m1 = Class.forName("java.lang.Object").getMethod("equals", new Class[] {
                Class.forName("java.lang.Object")
            });
            m0 = Class.forName("java.lang.Object").getMethod("hashCode", new Class[0]);
            m3 = Class.forName("lujing.sample.core.proxy.FooBarService").getMethod("getOrder", new Class[0]);
            m2 = Class.forName("java.lang.Object").getMethod("toString", new Class[0]);
        }
        catch(NoSuchMethodException nosuchmethodexception)
        {
            throw new NoSuchMethodError(nosuchmethodexception.getMessage());
        }
        catch(ClassNotFoundException classnotfoundexception)
        {
            throw new NoClassDefFoundError(classnotfoundexception.getMessage());
        }
    }
}

從上面的代碼能夠看到,代理類實現了須要代理的接口,同時每一個方法都是委託給 InvocationHandler 的 invoke 方法。在生成代理髮方法的時候,就知道 代理接口的方法是哪個。

相關文章
相關標籤/搜索