重要的类是Proxy. 首先要理解反射机制!
Spring的AOP就是用的动态代理机制。
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.Collection;
public class Demo {
public static void main(String[] args) throws Throwable {
//Collection 是java的集合接口
Class clazzproxy1 = Proxy.getProxyClass(Collection.class.getClassLoader(), Collection.class);
//打印结果为$Proxy0
System.out.println(clazzproxy1.getName());
System.out.println("-----------构造方法开始---------");
Constructor[] constructors = clazzproxy1.getConstructors();
for(Constructor con:constructors){
String name = con.getName();
StringBuilder sBuilder = new StringBuilder(name);
sBuilder.append('(');
Class[] clazzParams = con.getParameterTypes();
for(Class c:clazzParams)
sBuilder.append(c.getName()).append(" ");
sBuilder.append(')');
System.out.println(sBuilder);
}
Method[] methods = clazzproxy1.getMethods();
System.out.println("-----------方法列表开始---------");
StringBuilder sBuilder = new StringBuilder();
for(Method m:methods){
sBuilder.append(m.getName());
Class clazzParameters[] = m.getParameterTypes();
for(Class para:clazzParameters)
sBuilder.append('(').append(para.getName()).append(')');
sBuilder.append('\n');
}
System.out.println(sBuilder);
System.out.println("--------创建对象开始--------");
Constructor constructor = clazzproxy1.getConstructor(InvocationHandler.class);
//由于构造方法接收的是 InvocationHandler 接口类型。我们需要一个这个接口的实例
class MyInvocationHandler implements InvocationHandler{ //这里先什么都不写
@Override
public Object invoke(Object proxy, Method method, Object[] args)
throws Throwable {
return null;
}
}
Collection proxy1 = (Collection) constructor.newInstance(new MyInvocationHandler());
System.out.println(proxy1); //结果为:null. 因为proxy1.toString()为null,而不是proxy1为null,看后面解释
proxy1.clear();//可执行
//proxy1.size();//出错!!
}
}
最后一行注释掉了,运行会出错,只要是调用有返回值的方法都会出错!原因在后面解释。
打印结果:
$Proxy0
-----------构造方法开始---------
$Proxy0(java.lang.reflect.InvocationHandler,)
-----------方法列表开始---------
add(java.lang.Object)
hashCode
clear
equals(java.lang.Object)
toString
contains(java.lang.Object)
isEmpty
addAll(java.util.Collection)
iterator
size
toArray([Ljava.lang.Object;)
toArray
remove(java.lang.Object)
containsAll(java.util.Collection)
removeAll(java.util.Collection)
retainAll(java.util.Collection)
isProxyClass(java.lang.Class)
getProxyClass(java.lang.ClassLoader)([Ljava.lang.Class;)
getInvocationHandler(java.lang.Object)
newProxyInstance(java.lang.ClassLoader)([Ljava.lang.Class;)(java.lang.reflect.InvocationHandler)
wait
wait(long)(int)
wait(long)
getClass
notify
notifyAll
--------创建对象开始--------
null
简化上面的写法(匿名内部类):
Collection proxy2 = (Collection)Proxy.newProxyInstance(Collection.class.getClassLoader(),
new Class[]{Collection.class}, new InvocationHandler() {
public Object invoke(Object proxy, Method method, Object[] args)
throws Throwable {
return null;
}
});
再来添加一些实际的操作:(这里可以对args参数做一些过滤操作,就是修改传入的参数。)
这里new 了一个Arryalist 是因为 它是实现了 Collection接口的!
Collection proxy2 = (Collection)Proxy.newProxyInstance(Collection.class.getClassLoader(),
new Class[]{Collection.class}, new InvocationHandler() {
ArrayList target = new ArrayList();
public Object invoke(Object proxy, Method method, Object[] args)
throws Throwable {
return method.invoke(target, args);
}
});
proxy2.add(1);
proxy2.add(2);
System.out.println(proxy2.size());
分析:
1、动态生成的类实现了Collection接口(可以实现若干接口),生成的类有Collection接口中的所有方法和一个接收InvocationHandler参数的构造方法。
2、构造方法接收一个InvocationHandler对象.
内部实现机制(概述):
$Proxy0 implemets Collection{
InvocationHandler handler;
public $Proxy0(InvocationHadler hander){
this.handler = handler;
}
//从接口继承的方法,都会调用handler.invoke()
//包括从Object继承的 hashCode(0 toString() equals() 这3个方法会委托给handler执行
int size(){
return handler.invoke(this, this.getClass().getMethod("size"), null);
}
void clear(){
handler.invoke(this, this.getClass().getMethod("clear"), null);
}
}
分析第一段代码中的错误:
size()方法是要求返回值的,而我们的hanler.invoke()返回null。
System.out.println(proxy1); //结果为:null. 因为proxy1.toString() 也是调用的hanler.invoke() ,打印的自然是null,并不是说proxy1本身为null
官方介绍:
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.
To create a proxy for some interface Foo
:
InvocationHandler handler = new MyInvocationHandler(...); Class proxyClass = Proxy.getProxyClass( Foo.class.getClassLoader(), new Class[] { Foo.class }); Foo f = (Foo) proxyClass. getConstructor(new Class[] { InvocationHandler.class }). newInstance(new Object[] { handler });or more simply:
Foo f = (Foo) Proxy.newProxyInstance(Foo.class.getClassLoader(), new Class[] { Foo.class }, handler);
A dynamic proxy class (simply referred to as a proxy class below) is a class that implements a list of interfaces specified at runtime when the class is created, with behavior as described below. Aproxy interface is such an interface that is implemented by a proxy class. Aproxy instance is an instance of a proxy class. Each proxy instance has an associatedinvocation handler object, which implements the interfaceInvocationHandler
. A method invocation on a proxy instance through one of its proxy interfaces will be dispatched to theinvoke
method of the instance's invocation handler, passing the proxy instance, ajava.lang.reflect.Method
object identifying the method that was invoked, and an array of typeObject
containing the arguments. The invocation handler processes the encoded method invocation as appropriate and the result that it returns will be returned as the result of the method invocation on the proxy instance.
A proxy class has the following properties:
- Proxy classes are public, final, and not abstract.
- The unqualified name of a proxy class is unspecified. The space of class names that begin with the string
"$Proxy"
should be, however, reserved for proxy classes. - A proxy class extends
java.lang.reflect.Proxy
. - A proxy class implements exactly the interfaces specified at its creation, in the same order.
- If a proxy class implements a non-public interface, then it will be defined in the same package as that interface. Otherwise, the package of a proxy class is also unspecified. Note that package sealing will not prevent a proxy class from being successfully defined in a particular package at runtime, and neither will classes already defined by the same class loader and the same package with particular signers.
- Since a proxy class implements all of the interfaces specified at its creation, invoking
getInterfaces
on itsClass
object will return an array containing the same list of interfaces (in the order specified at its creation), invokinggetMethods
on itsClass
object will return an array ofMethod
objects that include all of the methods in those interfaces, and invokinggetMethod
will find methods in the proxy interfaces as would be expected. - The
Proxy.isProxyClass
method will return true if it is passed a proxy class-- a class returned byProxy.getProxyClass
or the class of an object returned byProxy.newProxyInstance
-- and false otherwise. - The
java.security.ProtectionDomain
of a proxy class is the same as that of system classes loaded by the bootstrap class loader, such asjava.lang.Object
, because the code for a proxy class is generated by trusted system code. This protection domain will typically be grantedjava.security.AllPermission
. - Each proxy class has one public constructor that takes one argument, an implementation of the interface
InvocationHandler
, to set the invocation handler for a proxy instance. Rather than having to use the reflection API to access the public constructor, a proxy instance can be also be created by calling theProxy.newInstance
method, which combines the actions of callingProxy.getProxyClass
with invoking the constructor with an invocation handler.
A proxy instance has the following properties:
- Given a proxy instance
proxy
and one of the interfaces implemented by its proxy classFoo
, the following expression will return true:proxy instanceof Foo
ClassCastException
):(Foo) proxy
- Each proxy instance has an associated invocation handler, the one that was passed to its constructor. The static
Proxy.getInvocationHandler
method will return the invocation handler associated with the proxy instance passed as its argument. - An interface method invocation on a proxy instance will be encoded and dispatched to the invocation handler's
invoke
method as described in the documentation for that method. - An invocation of the
hashCode
,equals
, ortoString
methods declared injava.lang.Object
on a proxy instance will be encoded and dispatched to the invocation handler'sinvoke
method in the same manner as interface method invocations are encoded and dispatched, as described above. The declaring class of theMethod
object passed toinvoke
will bejava.lang.Object
. Other public methods of a proxy instance inherited fromjava.lang.Object
are not overridden by a proxy class, so invocations of those methods behave like they do for instances ofjava.lang.Object
.
Methods Duplicated in Multiple Proxy Interfaces
When two or more interfaces of a proxy class contain a method with the same name and parameter signature, the order of the proxy class's interfaces becomes significant. When such aduplicate method is invoked on a proxy instance, theMethod
object passed to the invocation handler will not necessarily be the one whose declaring class is assignable from the reference type of the interface that the proxy's method was invoked through. This limitation exists because the corresponding method implementation in the generated proxy class cannot determine which interface it was invoked through. Therefore, when a duplicate method is invoked on a proxy instance, theMethod
object for the method in the foremost interface that contains the method (either directly or inherited through a superinterface) in the proxy class's list of interfaces is passed to the invocation handler'sinvoke
method, regardless of the reference type through which the method invocation occurred.
If a proxy interface contains a method with the same name and parameter signature as thehashCode
,equals
, ortoString
methods ofjava.lang.Object
, when such a method is invoked on a proxy instance, theMethod
object passed to the invocation handler will havejava.lang.Object
as its declaring class. In other words, the public, non-final methods ofjava.lang.Object
logically precede all of the proxy interfaces for the determination of whichMethod
object to pass to the invocation handler.
Note also that when a duplicate method is dispatched to an invocation handler, theinvoke
method may only throw checked exception types that are assignable to one of the exception types in thethrows
clause of the method inall of the proxy interfaces that it can be invoked through. If theinvoke
method throws a checked exception that is not assignable to any of the exception types declared by the method in one of the proxy interfaces that it can be invoked through, then an uncheckedUndeclaredThrowableException
will be thrown by the invocation on the proxy instance. This restriction means that not all of the exception types returned by invokinggetExceptionTypes
on theMethod
object passed to the invoke
method can necessarily be thrown successfully by theinvoke
method.