今天无意看proxy的使用。了解一下动态代理。

实例分析如下:

声明一个接口:

 



1. package
2.
3.
4. public interface
5. String getPackageInfo() ;
6. }

package com.czq.proxy;


public interface IPackageManager {
String getPackageInfo() ;
}

实现该接口



1. package
2.
3. import
4. import
5.
6. public class PackageManagerWoker implements
7. private Object mTarget = null;
8.
9. public
10. super();
11. this.mTarget = target;
12. }
13.
14. @Override
15. public Object invoke(Object proxy, Method method, Object[] args) throws
16.
17. "1"
18. "method:"
19. if (args != null) {
20. for (int i = 0; i < args.length; i++) {
21. "args[" + i + "]:"
22. }
23. }
24. Object result = method.invoke( mTarget, args);
25. "2"
26. return
27. }
28. }


package com.czq.proxy;

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

public class PackageManagerWoker implements InvocationHandler {
private Object mTarget = null;

public PackageManagerWoker(Object target) {
super();
this.mTarget = target;
}

@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {

System. out.println("1" );
System. out.println("method:" +method);
if (args != null) {
for (int i = 0; i < args.length; i++) {
System. out.println("args[" + i + "]:" + args[i]);
}
}
Object result = method.invoke( mTarget, args);
System. out.println("2" );
return result;
}
}

实现InvocationHandler 接口,关键之处在这

 




1. package
2.
3. import
4. import
5.
6. public class PackageManagerWoker implements
7. private Object mTarget = null;
8.
9. public
10. super();
11. this.mTarget = target;
12. }
13.
14. @Override
15. public Object invoke(Object proxy, Method method, Object[] args) throws
16.
17. "1"
18. "method:"
19. if (args != null) {
20. for (int i = 0; i < args.length; i++) {
21. "args[" + i + "]:"
22. }
23. }
24. Object result = method.invoke( mTarget, args);
25. "2"
26. return
27. }


package com.czq.proxy;

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

public class PackageManagerWoker implements InvocationHandler {
private Object mTarget = null;

public PackageManagerWoker(Object target) {
super();
this.mTarget = target;
}

@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {

System. out.println("1" );
System. out.println("method:" +method);
if (args != null) {
for (int i = 0; i < args.length; i++) {
System. out.println("args[" + i + "]:" + args[i]);
}
}
Object result = method.invoke( mTarget, args);
System. out.println("2" );
return result;
}


测试:

 



1. package
2.
3. import
4. import
5. import
6. import
7.
8. public class
9.
10. public static void
11. // 从源码中得知,设置这个值,可以把生成的代理类,输出出来。
12. "sun.misc.ProxyGenerator.saveGeneratedFiles", "true");
13.
14.
15. new
16. // System.out.println("pkgManger.toString:"+pkgManger.toString());
17. new
18. IPackageManager pm = (IPackageManager) Proxy.newProxyInstance(pkgManger.getClass().getClassLoader(),pkgManger
19. .getClass().getInterfaces(), woker);
20. // System.out.println("pm.getName:" +pm.getClass().getName())
21.
22. "pm.toString:"
23. System.out.println(pm.getPackageInfo());
24. }
25. }


package com.czq.proxy;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.lang.reflect.Proxy;

public class Test {

public static void main(String[] args) {
// 从源码中得知,设置这个值,可以把生成的代理类,输出出来。
System.getProperties().put("sun.misc.ProxyGenerator.saveGeneratedFiles", "true");


IPackageManager pkgManger = new PackageManagerImpl();
// System.out.println("pkgManger.toString:"+pkgManger.toString());
PackageManagerWoker woker = new PackageManagerWoker(pkgManger);
IPackageManager pm = (IPackageManager) Proxy.newProxyInstance(pkgManger.getClass().getClassLoader(),pkgManger
.getClass().getInterfaces(), woker);
// System.out.println("pm.getName:" +pm.getClass().getName())

System. out.println("pm.toString:" +pm.toString());
System.out.println(pm.getPackageInfo());
}
}


输出结果如下:

1

method:public ​​ Java​​.lang.String java.lang.Object.toString()

2

pm.toString:PackageManagerImpl

1

method:public abstract java.lang.String com.czq.proxy.IPackageManager.getPackageInfo()

2

com.czq.proxy

 

得出结论:

1 pm.getPackageInfo()方法会走到PackageManagerWoker的invoke方法。但是PackageManagerWoker不继承IPackageManager。不能强转成IPackageManager。也就是pm对象不是PackageManagerWoker对象。

那pm 是哪个对象,是什么类呢?还需要能强转成IPackageManager

 

打印pm的className

 



1. System.out.println("pm.getName:"


System.out.println("pm.getName:" +pm.getClass().getName())


得出的结果:

pm.getName:com.sun.proxy.$Proxy0

也就是pm对象是com.sun.proxy.$Proxy0这个类new出的对象。这个类是刚刚Proxy.newProxyInstance自动生成的class

那这个class里面写的是什么呢?

查看源码:Proxy.java

 


1. /**
2. * A factory function that generates, defines and returns the proxy class given
3. * the ClassLoader and array of interfaces.
4. */
5. private static final class
6. implements
7. {
8. // prefix for all proxy class names
9. private static final String proxyClassNamePrefix = "$Proxy";
10.
11. // next number to use for generation of unique proxy class names
12. private static final AtomicLong nextUniqueNumber = new
13.
14. @Override
15. public
16.
17. new
18. for
19. /*
20. * Verify that the class loader resolves the name of this
21. * interface to the same Class object.
22. */
23. null;
24. try
25. false, loader);
26. catch
27. }
28. if
29. throw new
30. " is not visible from class loader");
31. }
32. /*
33. * Verify that the Class object actually represents an
34. * interface.
35. */
36. if
37. throw new
38. " is not an interface");
39. }
40. /*
41. * Verify that this interface is not a duplicate.
42. */
43. if (interfaceSet.put(interfaceClass, Boolean.TRUE) != null
44. throw new
45. "repeated interface: "
46. }
47. }
48.
49. null; // package to define proxy class in
50.
51. /*
52. * Record the package of a non-public proxy interface so that the
53. * proxy class will be defined in the same package. Verify that
54. * all non-public proxy interfaces are in the same package.
55. */
56. for
57. int
58. if
59. String name = intf.getName();
60. int n = name.lastIndexOf('.'
61. 1) ? "" : name.substring(0, n + 1));
62. if (proxyPkg == null) {
63. proxyPkg = pkg;
64. else if
65. throw new
66. "non-public interfaces from different packages");
67. }
68. }
69. }
70.
71. if (proxyPkg == null) {
72. // if no non-public proxy interfaces, use com.sun.proxy package
73. ".";
74. }
75.
76. /*
77. * Choose a name for the proxy class to generate.
78. */
79. long
80. String proxyName = proxyPkg + proxyClassNamePrefix + num;
81.
82. /*
83. * Generate the specified proxy class.
84. */
85. byte[] proxyClassFile = ProxyGenerator.generateProxyClass(
86. proxyName, interfaces);
87. try
88. return
89. 0, proxyClassFile.length);
90. catch
91. /*
92. * A ClassFormatError here means that (barring bugs in the
93. * proxy class generation code) there was some other
94. * invalid aspect of the arguments supplied to the proxy
95. * class creation (such as virtual machine limitations
96. * exceeded).
97. */
98. throw new
99. }
100. }
101. }

/**
* A factory function that generates, defines and returns the proxy class given
* the ClassLoader and array of interfaces.
*/
private static final class ProxyClassFactory
implements BiFunction<ClassLoader, Class<?>[], Class<?>>
{
// prefix for all proxy class names
private static final String proxyClassNamePrefix = "$Proxy";

// next number to use for generation of unique proxy class names
private static final AtomicLong nextUniqueNumber = new AtomicLong();

@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 + ".";
}

/*
* 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);
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());
}
}
}


查看ProxyGenerator源码:通过ProxyGenerator 生成了这个class。

 



1. /**
2. * Generate a proxy class given a name and a list of proxy interfaces.
3. *
4. * @param name the class name of the proxy class
5. * @param interfaces proxy interfaces
6. * @param accessFlags access flags of the proxy class
7. */
8. public static byte[] generateProxyClass(final
9. Class<?>[] interfaces,
10. int
11. {
12. new
13. final byte[] classFile = gen.generateClassFile();
14.
15. if
16. java.security.AccessController.doPrivileged(
17. new
18. public
19. try
20. int i = name.lastIndexOf('.');
21. Path path;
22. if (i > 0) {
23. 0, i).replace('.', File.separatorChar));
24. Files.createDirectories(dir);
25. 1, name.length()) + ".class");
26. else
27. ".class");
28. }
29. Files.write(path, classFile);
30. return null;
31. catch
32. throw new
33. "I/O exception saving generated file: "
34. }
35. }
36. });
37. }
38.
39. return
40. }

/**
* Generate a proxy class given a name and a list of proxy interfaces.
*
* @param name the class name of the proxy class
* @param interfaces proxy interfaces
* @param accessFlags access flags of the proxy class
*/
public static byte[] generateProxyClass(final String name,
Class<?>[] interfaces,
int accessFlags)
{
ProxyGenerator gen = new ProxyGenerator(name, interfaces, accessFlags);
final byte[] classFile = gen.generateClassFile();

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;
}





发现 saveGeneratedFiles 为true报错生成的class的源码。

这个saveGeneratedFiles 怎么赋值呢?

 



1. /** debugging flag for saving generated class files */
2. private final static boolean
3. java.security.AccessController.doPrivileged(
4. new
5. "sun.misc.ProxyGenerator.saveGeneratedFiles")).booleanValue();


/** debugging flag for saving generated class files */
private final static boolean saveGeneratedFiles =
java.security.AccessController.doPrivileged(
new GetBooleanAction(
"sun.misc.ProxyGenerator.saveGeneratedFiles")).booleanValue();


也就是把sun.misc.ProxyGenerator.saveGeneratedFiles 改成true就可以输出结果了。

 



1. // 从源码中得知,设置这个值,可以把生成的代理类,输出出来。
2. "sun.misc.ProxyGenerator.saveGeneratedFiles", "true");


// 从源码中得知,设置这个值,可以把生成的代理类,输出出来。
System.getProperties().put("sun.misc.ProxyGenerator.saveGeneratedFiles", "true");


 注意,需要再工程更目录下,增加 com/sun/proxy目录,否则会报错如下:

 

Exception in thread "main" java.lang.InternalError: I/O exception saving generated file:java.io.FileNotFoundException : com\sun\proxy\$Proxy0.class (系统找不到指定的路径。)

     at sun.misc.ProxyGenerator$1.run(ProxyGenerator.java:336 )

     at sun.misc.ProxyGenerator$1.run(ProxyGenerator.java:327 )

     at java.security.AccessController.doPrivileged( Native Method)

     at sun.misc.ProxyGenerator.generateProxyClass( ProxyGenerator.java:326)

     at java.lang.reflect.Proxy$ProxyClassFactory.apply( Proxy.java:672)

     at java.lang.reflect.Proxy$ProxyClassFactory.apply( Proxy.java:592)

     at java.lang.reflect.WeakCache$Factory.get( WeakCache.java:244)

     at java.lang.reflect.WeakCache.get(WeakCache.java:141 )

     at java.lang.reflect.Proxy.getProxyClass0(Proxy.java:455 )

     at java.lang.reflect.Proxy.newProxyInstance( Proxy.java:738)

     at com.czq.proxy.Test.main( Test.java:18 )

 

把proxy0输出的结果如下:

反编译看看proxy0是内容是啥,有什么秘密

 


1. package
2.
3. import
4. import
5. import
6. import
7. import
8.
9. public final class $Proxy0 extends
10. implements
11. {
12. private static Method m3; // 生成对应的方法对象
13. private static
14. private static
15. private static
16. // proxy0 继承Proxy,实现IPackageManager 接口,需要传入 InvocationHandler,初始化对应的h对象。
17. // 我们的h对象就是PackageManagerWoker,所以我们会调用到PackageManagerWoker的 invoke方法。
18. // 所以是proxy0,调用InvocationHandler的 invoke 方法,传入对应的方法。InvocationHandler 放射调用对应的tagret中的方法。
19. public
20. throws
21. {
22. super(paramInvocationHandler);
23. }
24.
25. public final
26. throws
27. {
28. try
29. {
30. return (String)this.h.invoke(this, m3, null);
31. }
32. catch
33. {
34. throw
35. }
36. catch
37. {
38. }
39. throw new
40. }
41.
42. public final boolean
43. throws
44. {
45. try
46. {
47. return ((Boolean)this.h.invoke(this, m1, new
48. }
49. catch
50. {
51. throw
52. }
53. catch
54. {
55. }
56. throw new
57. }
58.
59. public final int
60. throws
61. {
62. try
63. {
64. return ((Integer)this.h.invoke(this, m0, null)).intValue();
65. }
66. catch
67. {
68. throw
69. }
70. catch
71. {
72. }
73. throw new
74. }
75.
76. public final
77. throws
78. {
79. try
80. {
81. return (String)this.h.invoke(this, m2, null);
82. }
83. catch
84. {
85. throw
86. }
87. catch
88. {
89. }
90. throw new
91. }
92.
93. static
94. {
95. try
96. {
97. // 把各个方法,对应到成员变量上
98. "com.czq.proxy.IPackageManager").getMethod("getPackageInfo", new Class[0]);
99. "java.lang.Object").getMethod("equals", new Class[] { Class.forName("java.lang.Object") });
100. "java.lang.Object").getMethod("hashCode", new Class[0]);
101. "java.lang.Object").getMethod("toString", new Class[0]);
102. return;
103. }
104. catch
105. {
106. throw new
107. }
108. catch
109. {
110. }
111. throw new
112. }
113. }

package com.sun.proxy;

import com.czq.proxy.IPackageManager;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.lang.reflect.UndeclaredThrowableException;

public final class $Proxy0 extends Proxy
implements IPackageManager
{
private static Method m3; // 生成对应的方法对象
private static Method m1;
private static Method m0;
private static Method m2;
// proxy0 继承Proxy,实现IPackageManager 接口,需要传入 InvocationHandler,初始化对应的h对象。
// 我们的h对象就是PackageManagerWoker,所以我们会调用到PackageManagerWoker的 invoke方法。
// 所以是proxy0,调用InvocationHandler的 invoke 方法,传入对应的方法。InvocationHandler 放射调用对应的tagret中的方法。
public $Proxy0(InvocationHandler paramInvocationHandler)
throws
{
super(paramInvocationHandler);
}

public final String getPackageInfo()
throws
{
try
{
return (String)this.h.invoke(this, m3, null);
}
catch (RuntimeException localRuntimeException)
{
throw localRuntimeException;
}
catch (Throwable localThrowable)
{
}
throw new UndeclaredThrowableException(localThrowable);
}

public final boolean equals(Object paramObject)
throws
{
try
{
return ((Boolean)this.h.invoke(this, m1, new Object[] { paramObject })).booleanValue();
}
catch (RuntimeException localRuntimeException)
{
throw localRuntimeException;
}
catch (Throwable localThrowable)
{
}
throw new UndeclaredThrowableException(localThrowable);
}

public final int hashCode()
throws
{
try
{
return ((Integer)this.h.invoke(this, m0, null)).intValue();
}
catch (RuntimeException localRuntimeException)
{
throw localRuntimeException;
}
catch (Throwable localThrowable)
{
}
throw new UndeclaredThrowableException(localThrowable);
}

public final String toString()
throws
{
try
{
return (String)this.h.invoke(this, m2, null);
}
catch (RuntimeException localRuntimeException)
{
throw localRuntimeException;
}
catch (Throwable localThrowable)
{
}
throw new UndeclaredThrowableException(localThrowable);
}

static
{
try
{
// 把各个方法,对应到成员变量上
m3 = Class.forName("com.czq.proxy.IPackageManager").getMethod("getPackageInfo", new Class[0]);
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]);
m2 = Class.forName("java.lang.Object").getMethod("toString", new Class[0]);
return;
}
catch (NoSuchMethodException localNoSuchMethodException)
{
throw new NoSuchMethodError(localNoSuchMethodException.getMessage());
}
catch (ClassNotFoundException localClassNotFoundException)
{
}
throw new NoClassDefFoundError(localClassNotFoundException.getMessage());
}
}
package com.sun.proxy;

import com.czq.proxy.IPackageManager;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.lang.reflect.UndeclaredThrowableException;

public final class $Proxy0 extends Proxy
implements IPackageManager
{
private static Method m3; // 生成对应的方法对象
private static Method m1;
private static Method m0;
private static Method m2;
// proxy0 继承Proxy,实现IPackageManager 接口,需要传入 InvocationHandler,初始化对应的h对象。
// 我们的h对象就是PackageManagerWoker,所以我们会调用到PackageManagerWoker的 invoke方法。
// 所以是proxy0,调用InvocationHandler的 invoke 方法,传入对应的方法。InvocationHandler 放射调用对应的tagret中的方法。
public $Proxy0(InvocationHandler paramInvocationHandler)
throws
{
super(paramInvocationHandler);
}

public final String getPackageInfo()
throws
{
try
{
return (String)this.h.invoke(this, m3, null);
}
catch (RuntimeException localRuntimeException)
{
throw localRuntimeException;
}
catch (Throwable localThrowable)
{
}
throw new UndeclaredThrowableException(localThrowable);
}

public final boolean equals(Object paramObject)
throws
{
try
{
return ((Boolean)this.h.invoke(this, m1, new Object[] { paramObject })).booleanValue();
}
catch (RuntimeException localRuntimeException)
{
throw localRuntimeException;
}
catch (Throwable localThrowable)
{
}
throw new UndeclaredThrowableException(localThrowable);
}

public final int hashCode()
throws
{
try
{
return ((Integer)this.h.invoke(this, m0, null)).intValue();
}
catch (RuntimeException localRuntimeException)
{
throw localRuntimeException;
}
catch (Throwable localThrowable)
{
}
throw new UndeclaredThrowableException(localThrowable);
}

public final String toString()
throws
{
try
{
return (String)this.h.invoke(this, m2, null);
}
catch (RuntimeException localRuntimeException)
{
throw localRuntimeException;
}
catch (Throwable localThrowable)
{
}
throw new UndeclaredThrowableException(localThrowable);
}

static
{
try
{
// 把各个方法,对应到成员变量上
m3 = Class.forName("com.czq.proxy.IPackageManager").getMethod("getPackageInfo", new Class[0]);
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]);
m2 = Class.forName("java.lang.Object").getMethod("toString", new Class[0]);
return;
}
catch (NoSuchMethodException localNoSuchMethodException)
{
throw new NoSuchMethodError(localNoSuchMethodException.getMessage());
}
catch (ClassNotFoundException localClassNotFoundException)
{
}
throw new NoClassDefFoundError(localClassNotFoundException.getMessage());
}
}



结论如下:

 

1.    proxy0继承Proxy,实现IPackageManager 接口,需要传入 InvocationHandler,初始化对应的h对象。

2.    我们的h对象就是PackageManagerWoker,所以我们会调用到PackageManagerWoker的 invoke方法。

3.    所以是proxy0,调用InvocationHandler的 invoke 方法,传入对应的方法。InvocationHandler 放射调用对应的tagret中的方法。套了2层。