一、Java創建動態代理對象步驟
java動態代理創建對象的過程爲如下步驟:
1. 通過實現InvocationHandler接口創建自己的調用處理器。
調用處理器實現InvocationHandler接口的invoke方法。代理類的方法調用會將代理對象、調用方法的Method對象、方法的參數數組傳遞給調用處理器對象的 invoke方法,我們需要在invoke方法中,將方法調用委託給被代理對象執行。所以調用處理器內部通常包含指向委託類實例的引用,用於真正執行分派轉發過來的方法調用。
public class DynamicProxyHandler implements InvocationHandler {
private Object proxied;
public DynamicProxyHandler(Object proxied) {
super();
this.proxied = proxied;
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
.......
return method.invoke(proxied,args );
}
}
InvocationHandler handler = new DynamicProxyHandler(..);
2.通過爲 Proxy 類指定 ClassLoader 對象和一組 interface 來創建動態代理類;
// 通過 Proxy 爲包括 Interface 接口在內的一組接口動態創建代理類的類對象
Class clazz = Proxy.getProxyClass(classLoader, new Class[] { Interface.class, ... });
3.通過反射機制獲得動態代理類的構造函數,其唯一參數類型是調用處理器接口類型;
// 通過反射從生成的類對象獲得構造函數對象
Constructor constructor = clazz.getConstructor(new Class[] { InvocationHandler.class });
4.通過構造函數創建動態代理類實例,構造時調用處理器對象作爲參數被傳入。
// 通過構造函數對象創建動態代理類實例
Interface Proxy = (Interface)constructor.newInstance(new Object[] { handler });
Proxy類newProxyInstance方法直接創建代理對象
Proxy類的newProxyInstance靜態方法封裝了上面2-4流程:
InvocationHandler handler = new DynamicProxyHandler(..);
// 通過 Proxy 直接創建動態代理類實例
Interface proxy = (Interface)Proxy.newProxyInstance( classLoader,
new Class[] { Interface.class },
handler );
二、使用示例
Proxy類可以對一組接口進行代理。被代理類和代理類實現了相同的接口。這裏以一個公共接口爲例
//Interface.java
public interface Interface {
public void doSomething();
public void somethingElse(String arg);
}
被代理類定義如下:
//RealObject.java
public class RealObject implements Interface {
@Override
public void doSomething() {
System.out.println("doSomething");
}
@Override
public void somethingElse(String arg) {
System.out.println("somethingElse "+arg);
}
}
調用處理器接口實現如下,方法調用前打印方法名和方法參數:
public class DynamicProxyHandler implements InvocationHandler {
private Object proxied;
public DynamicProxyHandler(Object proxied) {
super();
this.proxied = proxied;
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
System.out.println("**** proxy: "+proxy.getClass()+" ,method: "+method.getName()+" ,args: "+args);
if(args!=null)
for(Object arg: args){
System.out.println(" "+arg);
}
return method.invoke(proxied,args );
}
}
動態代理實現如下:
public class SimpleDynamicProxy {
public static void consumer(Interface iface){
iface.doSomething();
iface.somethingElse("bonobo");
}
public static void main(String[] args) {
RealObject real = new RealObject();
consumer(real);
Interface proxy = (Interface) Proxy.newProxyInstance(Interface.class.getClassLoader(), new Class[]{Interface.class}, new DynamicProxyHandler(real));
consumer(proxy);
}
}
執行後輸出:
doSomething
somethingElse bonobo
**** proxy: class com.sun.proxy.$Proxy0 ,method: doSomething ,args: null
doSomething
**** proxy: class com.sun.proxy.$Proxy0 ,method: somethingElse ,args: [Ljava.lang.Object;@6bc7c054
bonobo
somethingElse bonobo
可以看到打印出了被調用的方法名和方法參數
三、動態代理相關類源碼解析
1.java.lang.reflect.InvocationHandler
InvocationHandler爲調用處理接口。每個生成的代理對象都擁有一個實現InvocationHandler接口的調用處理類。當生成的代理對象調用自己的方法時,會把自身引用和調用的方法對象傳遞給該方法集中處理。
@procy 代理對象的實例
@method 被調用的方法對象
@args 被調用方法的實際參數值
public interface InvocationHandler {
public Object invoke(Object proxy, Method method, Object[] args)
throws Throwable;
}
2. java.lang.reflect.Proxy類
Proxy 類提供靜態方法用來創建一組接口的動態代理類和動態代理類的實例。它是這些靜態方法創建的動態代理類的父類。
Proxy的主要靜態成員變量:
//代理類構造器參數類型
private static final Class<?>[]constructorParams ={ InvocationHandler.class };
//代理對象的調用處理器對象的引用
protected InvocationHandler h;
// 映射表:用於維護類裝載器對象到其對應的代理類緩存 ClassLoder-Interfaces-ProxyClass
private static final WeakCache<ClassLoader, Class<?>[], Class<?>>
proxyClassCache = new WeakCache<>(new KeyFactory(), new ProxyClassFactory());
Proxy的構造方法
//禁止外部調用,內部也從未調用
private Proxy() {
}
// 由於 Proxy 內部從不直接調用構造函數,所以 protected 意味着只有子類可以調用
protected Proxy(InvocationHandler h) {
Objects.requireNonNull(h);
this.h = h;
}
Proxy的靜態方法
// 方法 1: 該方法用於獲取指定代理對象所關聯的調用處理器
public static InvocationHandler getInvocationHandler(Object proxy)
// 方法 2:該方法用於獲取關聯於指定類裝載器和一組接口的動態代理類的類對象
public static Class<?> getProxyClass(ClassLoader loader,
Class<?>... interfaces)
// 方法 3:該方法用於判斷指定類對象是否是一個動態代理類
public static boolean isProxyClass(Class<?> cl)
// 方法 4:該方法用於爲指定類裝載器、一組接口及調用處理器生成動態代理類實例
public static Object newProxyInstance(ClassLoader loader,
Class<?>[] interfaces,InvocationHandler h)
Proxy的生成過程
1.newProxyInstance方法
newProxyInstance方法調用getProxyClass0方法獲取代理類
public static Object newProxyInstance(ClassLoader loader,
Class<?>[] interfaces,
InvocationHandler h)
throws IllegalArgumentException
{
//檢查InvocationHandler是否爲null,如果爲null直接拋異常
Objects.requireNonNull(h);
final Class<?>[] intfs = interfaces.clone();
final SecurityManager sm = System.getSecurityManager();
if (sm != null) {
checkProxyAccess(Reflection.getCallerClass(), loader, intfs);
}
/*
* Look up or generate the designated proxy class.
*/
// 獲得與指定類裝載器和一組接口相關的代理類類型對象
Class<?> cl = getProxyClass0(loader, intfs);
/*
* Invoke its constructor with the designated invocation handler.
*/
try {
if (sm != null) {
checkNewProxyPermission(Reflection.getCallerClass(), cl);
}
// 通過反射獲取構造函數對象並生成代理類實例
final Constructor<?> cons = cl.getConstructor(constructorParams);
final InvocationHandler ih = h;
if (!Modifier.isPublic(cl.getModifiers())) {
AccessController.doPrivileged(new PrivilegedAction<Void>() {
public Void run() {
cons.setAccessible(true);
return null;
}
});
}
return cons.newInstance(new Object[]{h});
} catch (IllegalAccessException|InstantiationException e) {
throw new InternalError(e.toString(), e);
} catch (InvocationTargetException e) {
Throwable t = e.getCause();
if (t instanceof RuntimeException) {
throw (RuntimeException) t;
} else {
throw new InternalError(t.toString(), t);
}
} catch (NoSuchMethodException e) {
throw new InternalError(e.toString(), e);
}
}
2.getProxyClass0方法
.getProxyClass0方法通過映射表緩存獲取代理類。沒有的話通過ProxyClassFactory類創建代理類
/**
* Generate a proxy class. Must call the checkProxyAccess method
* to perform permission checks before calling this.
*/
private static Class<?> getProxyClass0(ClassLoader loader,
Class<?>... interfaces) {
if (interfaces.length > 65535) {
throw new IllegalArgumentException("interface limit exceeded");
}
// If the proxy class defined by the given loader implementing
// the given interfaces exists, this will simply return the cached copy;
// otherwise, it will create the proxy class via the ProxyClassFactory
return proxyClassCache.get(loader, interfaces);
}
3.靜態內部類ProxyClassFactory的apply方法
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
int accessFlags = Modifier.PUBLIC | Modifier.FINAL;
/*
* 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)) {
accessFlags = Modifier.FINAL;
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 + ".";
}
/*
* Choose a name for the proxy class to generate.
*/
long num = nextUniqueNumber.getAndIncrement();
String proxyName = proxyPkg + proxyClassNamePrefix + num;
//通過類加載器和接口生成代理類字節碼
/*
* Generate the specified proxy class.
*/
byte[] proxyClassFile = ProxyGenerator.generateProxyClass(
proxyName, interfaces, accessFlags);
try {
//加載字節碼
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());
}
}
}
可以看到在apply方法中,下面這行代碼生成了內部類
/*
* Generate the specified proxy class.
*/
byte[] proxyClassFile = ProxyGenerator.generateProxyClass(
proxyName, interfaces, accessFlags);
4.ProxyGenerator類
ProxyGenerator類源碼:http://www.docjar.com/html/api/sun/misc/ProxyGenerator.java.html
ProxyGenerater類源碼解析:https://www.cnblogs.com/liuyun1995/p/8144706.html
Eclipse導入該ProxyGenerater:導入某些特殊Jar包中的類
自己實現生成代理類的工具類
該工具類對指定接口生成代理類
package com.lengyu.proxy;
import java.io.FileOutputStream;
import java.io.IOException;
import sun.misc.ProxyGenerator;
public class ProxyUtils {
/*
* Save proxy class to path
*
* @param path path to save proxy class
* @param proxyClassName name of proxy class
* @param interfaces interfaces of proxy class
* @return
*/
public static boolean saveProxyClass(String path, String proxyClassName, Class[] interfaces) {
if (proxyClassName == null || path == null) {
return false;
}
// get byte of proxy class
byte[] classFile = ProxyGenerator.generateProxyClass(proxyClassName, interfaces);
FileOutputStream out = null;
try {
out = new FileOutputStream(path);
out.write(classFile);
out.flush();
return true;
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return false;
}
}
在main方法中調用該類,生成代理類的.calss文件
public class SimpleDynamicProxy {
public static void consumer(Interface iface){
iface.doSomething();
iface.somethingElse("bonobo");
}
public static void main(String[] args) {
RealObject real = new RealObject();
consumer(real);
Interface proxy = (Interface) Proxy.newProxyInstance(Interface.class.getClassLoader(), new Class[]{Interface.class}, new DynamicProxyHandler(real));
consumer(proxy);
ProxyUtils.saveProxyClass("K://ProxySubject.class","ProxySubject",new Class[]{Interface.class});
//createProxyClassFile() ;
}
public static void createProxyClassFile()
{
String name = "ProxySubject";
byte[] data = ProxyGenerator.generateProxyClass( name, new Class[] { Interface.class } );
try
{
FileOutputStream out = new FileOutputStream( name + ".class" );
out.write( data );
out.close();
}
catch( Exception e )
{
e.printStackTrace();
}
}
}
用反彙編生成後的ProxySubject.class文件,可以看到Proxy的java代嗎
import com.lengyu.proxy.Interface;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.lang.reflect.UndeclaredThrowableException;
public final class ProxySubject
extends Proxy
implements Interface
{
private static Method m1;
private static Method m3;
private static Method m2;
private static Method m4;
private static Method m0;
public ProxySubject(InvocationHandler paramInvocationHandler)
{
super(paramInvocationHandler);
}
public final boolean equals(Object paramObject)
{
try
{
return ((Boolean)this.h.invoke(this, m1, new Object[] { paramObject })).booleanValue();
}
catch (Error|RuntimeException localError)
{
throw localError;
}
catch (Throwable localThrowable)
{
throw new UndeclaredThrowableException(localThrowable);
}
}
public final void doSomething()
{
try
{
this.h.invoke(this, m3, null);
return;
}
catch (Error|RuntimeException localError)
{
throw localError;
}
catch (Throwable localThrowable)
{
throw new UndeclaredThrowableException(localThrowable);
}
}
public final String toString()
{
try
{
return (String)this.h.invoke(this, m2, null);
}
catch (Error|RuntimeException localError)
{
throw localError;
}
catch (Throwable localThrowable)
{
throw new UndeclaredThrowableException(localThrowable);
}
}
public final void somethingElse(String paramString)
{
try
{
this.h.invoke(this, m4, new Object[] { paramString });
return;
}
catch (Error|RuntimeException localError)
{
throw localError;
}
catch (Throwable localThrowable)
{
throw new UndeclaredThrowableException(localThrowable);
}
}
public final int hashCode()
{
try
{
return ((Integer)this.h.invoke(this, m0, null)).intValue();
}
catch (Error|RuntimeException localError)
{
throw localError;
}
catch (Throwable localThrowable)
{
throw new UndeclaredThrowableException(localThrowable);
}
}
static
{
try
{
m1 = Class.forName("java.lang.Object").getMethod("equals", new Class[] { Class.forName("java.lang.Object") });
m3 = Class.forName("com.lengyu.proxy.Interface").getMethod("doSomething", new Class[0]);
m2 = Class.forName("java.lang.Object").getMethod("toString", new Class[0]);
m4 = Class.forName("com.lengyu.proxy.Interface").getMethod("somethingElse", new Class[] { Class.forName("java.lang.String") });
m0 = Class.forName("java.lang.Object").getMethod("hashCode", new Class[0]);
return;
}
catch (NoSuchMethodException localNoSuchMethodException)
{
throw new NoSuchMethodError(localNoSuchMethodException.getMessage());
}
catch (ClassNotFoundException localClassNotFoundException)
{
throw new NoClassDefFoundError(localClassNotFoundException.getMessage());
}
}
}
項目附件:https://download.csdn.net/download/u012417380/10346419
參考文章: