一. 代理模式例子:
- 目标类及代理类统一接口
/**
* 用户操作接口
* Created by Deity on 2017/11/12.
*/
public interface IUserService {
/**查询所有用户*/
void queryAllUser();
}
- 目标实现类
/**
* 用户接口实现类
* Created by Deity on 2017/11/12.
*/
public class UserServiceImpl implements IUserService {
/**
* 查询所有用户
*/
@Override
public void queryAllUser() {
System.out.println("查询所有的用户");
}
}
- 自定义的代理模式处理程序
/**
* 自定义的代理模式处理程序
* Created by Deity on 2017/11/12.
*/
public class UserServiceInvocationHandler implements InvocationHandler{
/**需要被代理的目标对象*/
private Object object;
public UserServiceInvocationHandler(Object object){
super();
this.object = object;
}
/**
* Processes a method invocation on a proxy instance and returns
* the result. This method will be invoked on an invocation handler
* when a method is invoked on a proxy instance that it is
* associated with.
*
* @param proxy the proxy instance that the method was invoked on
* @param method the {@code Method} instance corresponding to
* the interface method invoked on the proxy instance. The declaring
* class of the {@code Method} object will be the interface that
* the method was declared in, which may be a superinterface of the
* proxy interface that the proxy class inherits the method through.
* @param args an array of objects containing the values of the
* arguments passed in the method invocation on the proxy instance,
* or {@code null} if interface method takes no arguments.
* Arguments of primitive types are wrapped in instances of the
* appropriate primitive wrapper class, such as
* {@code java.lang.Integer} or {@code java.lang.Boolean}.
* @return the value to return from the method invocation on the
* proxy instance. If the declared return type of the interface
* method is a primitive type, then the value returned by
* this method must be an instance of the corresponding primitive
* wrapper class; otherwise, it must be a type assignable to the
* declared return type. If the value returned by this method is
* {@code null} and the interface method's return type is
* primitive, then a {@code NullPointerException} will be
* thrown by the method invocation on the proxy instance. If the
* value returned by this method is otherwise not compatible with
* the interface method's declared return type as described above,
* a {@code ClassCastException} will be thrown by the method
* invocation on the proxy instance.
* @throws Throwable the exception to throw from the method
* invocation on the proxy instance. The exception's type must be
* assignable either to any of the exception types declared in the
* {@code throws} clause of the interface method or to the
* unchecked exception types {@code java.lang.RuntimeException}
* or {@code java.lang.Error}. If a checked exception is
* thrown by this method that is not assignable to any of the
* exception types declared in the {@code throws} clause of
* the interface method, then an
* {@link UndeclaredThrowableException} containing the
* exception that was thrown by this method will be thrown by the
* method invocation on the proxy instance.
* @see UndeclaredThrowableException
*/
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
System.out.println("before method invoke");
Object result = method.invoke(object,args);
System.out.println("after method invoke");
return result;
}
/**获取目标对象的代理对象*/
public Object obtainProxyInstance(){
return Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(),object.getClass().getInterfaces(),this);
}
}
4.代理模式用例测试
/**
* 代理模式用例测试
*/
public class ExampleUnitTest {
@Test
public void testPoxy() throws Exception {
IUserService userService = new UserServiceImpl();
UserServiceInvocationHandler userServiceInvocationHandler = new UserServiceInvocationHandler(userService);
IUserService proxyUserService = (IUserService) userServiceInvocationHandler.obtainProxyInstance();
proxyUserService.queryAllUser();
}
}
-
运行结果:
运行结果
二.动态代理中底层为我们做了什么
可以发现,在此过程中,我们实现了一个自定义的代理模式调用处理程序,并重写的了这个接口中的invoke()方法.这个invoke()方法在什么情况下会执行呢?
invoke()方法是proxy实例 处理方法调用并返回结果的入口,当一个proxy实例调用方法时,与之关联的InvocationHandler 的invoke()方法就会执行.
拿我们上面的例子来说,proxyUserService调用了queryAllUser()方法会触发UserServiceInvocationHandler 执行 invoke() 方法。
我们发现这个方法中存在3个参数
proxy 该方法被调用的代理实例,就是上面例子中的proxyUserService实例.
method 对应于在代理实例上调用的接口方法,Method对象的声明类将是方法声明的接口,它可能是代理类继承方法的代理接口的超级接口。
args 代理实例中方法调用的入参(也有可能是空值)
关于返回值: 如果接口方法的声明返回类型是基本类型,则此方法返回的值必须是相应基本包装类的实例,否则,它必须是可分配给声明的返回类型的类型(有点绕口),如果此方法返回的值为null,并且接口方法的返回类型为原始类型,则代理实例上的方法调用将抛出NullPointerException异常。 如果此方法返回的值与上述的接口方法的声明返回类型不兼容,则代理实例上的方法调用将抛出ClassCastException。
上面我们说了:当一个proxy实例调用方法时,与之关联的InvocationHandler 的invoke()方法就会执行,那么这个proxy实例是怎么来的呢?
三.生成proxy实例
跟着我看下这个生成Proxy实例的方法签名:
/**
*返回指定接口的动态构建类的实例,返回的proxy实例的方法调用,
接口必须对类加载器可见(public修饰符,protect修饰符),并且不允许重
复,非public修饰的接口必须在同一个包下定义
*/
public static Object newProxyInstance (ClassLoader loader, Class[]<?>
interfaces, InvocationHandler invocationHandler)
看下这个方法的源码实现
public static Object newProxyInstance(ClassLoader loader,
Class<?>[] interfaces,
InvocationHandler h)
throws IllegalArgumentException{
//如果没有定义调度处理程序,直接抛出空指针异常
if (h == null) {
throw new NullPointerException();
}
//查找或者生成指定的代理类
Class<?> cl = getProxyClass0(loader, interfaces);
//使用指定的调度处理程序调用其构造函数
try {
//其中constructorParams是代理类构造函数的参数类型(一个常量)
final Constructor<?> cons=cl.getConstructor(constructorParams);
return newInstance(cons, h);
} catch (NoSuchMethodException e) {
throw new InternalError(e.toString());
}
}
我们发现我们自定义的调度处理程序以入参的形式传递到生成代理实例的构造函数中,这也间接解释了为什么proxy实例的方法被调用会触发InvocationHandler 的invoke()方法执行的一个原因.
newProxyInstance()方法给我们引出了3个疑点。
- getProxyClass0(loader, interfaces)
- cl.getConstructor(constructorParams)
- newInstance(cons, h)
以上三个方法又做了什么
/**生成一个代理类,在调用此方法之前,需要调用checkProxyAccess方法执行权限检测 */
private static Class<?> getProxyClass0(ClassLoader loader,
Class<?>... interfaces)
来看下这个方法的源码(非官方源码,非关键内容已删减)
private static Class<?> getProxyClass0(ClassLoader loader,
Class<?>... interfaces) {
//接口数量限制,一般不会出现这种情况.
if (interfaces.length > 65535) {
throw new IllegalArgumentException("interface limit exceeded");
}
Class<?> proxyClass = null;
//收集接口名称以用作代理类缓存的关键字
String[] interfaceNames = new String[interfaces.length];
//用于检测重复
Set<Class<?>> interfaceSet = new HashSet<>();
for (int i = 0; i < interfaces.length; i++) {
/*
* 验证类加载器是否将此接口的名称解析为同一个Class对象。
* 或者说这个接口对类加载器是否可见
*/
....
//验证Class对象是否是一个接口。
....
//确认这个接口不重复
....
//存储Key值
interfaceNames[i] = interfaceName;
}
/*
* Using string representations of the proxy interfaces as
* keys in the proxy class cache (instead of their Class
* objects) is sufficient because we require the proxy
* interfaces to be resolvable by name through the supplied
* class loader, and it has the advantage that using a string
* representation of a class makes for an implicit weak
* reference to the class.
*/
List<String> key = Arrays.asList(interfaceNames);
//为类加载器查找或创建代理类缓存
//这个映射将在这个方法的持续时间内保持有效,而不需要进一步的
//同步,因为只有当类加载器变得不可达时,映射才会被移除。
Map<List<String>, Object> cache;
synchronized (loaderToCache) {
cache = loaderToCache.get(loader);
if (cache == null) {
cache = new HashMap<>();
loaderToCache.put(loader, cache);
}
}
/*
* 使用Key值查找代理类缓存接口类表,这种查找可能会有三种情况
* 1.当前的类加载器没有实现了接口列表的代理类.返回空值
* 2.如果当前正在生成接口列表的代理类,返回
* pendingGenerationMarker对象
* 3.如果已经生成了接口列表的代理类,返回代理类对象的弱引用
*/
synchronized (cache) {
/*
* Note that we need not worry about reaping the cache for
* entries with cleared weak references because if a proxy class
* has been garbage collected, its class loader will have been
* garbage collected as well, so the entire cache will be reaped
* from the loaderToCache map.
*/
do {
Object value = cache.get(key);
if (value instanceof Reference) {
proxyClass = (Class<?>) ((Reference) value).get();
}
if (proxyClass != null) {
// proxy class already generated: return it
return proxyClass;
} else if (value == pendingGenerationMarker) {
// proxy class being generated: wait for it
try {
cache.wait();
} catch (InterruptedException e) {
/*
* The class generation that we are waiting for should
* take a small, bounded time, so we can safely ignore
* thread interrupts here.
*/
}
continue;
} else {
/*
* No proxy class for this list of interfaces has been
* generated or is being generated, so we will go and
* generate it now. Mark it as pending generation.
*/
cache.put(key, pendingGenerationMarker);
break;
}
} while (true);
}
try {
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 (int i = 0; i < interfaces.length; i++) {
int flags = interfaces[i].getModifiers();
if (!Modifier.isPublic(flags)) {
String name = interfaces[i].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 the default package.
proxyPkg = "";
}
{
// Android-changed: Generate the proxy directly instead of calling
// through to ProxyGenerator.
List<Method> methods = getMethods(interfaces);
Collections.sort(methods, ORDER_BY_SIGNATURE_AND_SUBTYPE);
validateReturnTypes(methods);
List<Class<?>[]> exceptions = deduplicateAndGetExceptions(methods);
Method[] methodsArray = methods.toArray(new Method[methods.size()]);
Class<?>[][] exceptionsArray = exceptions.toArray(new Class<?>[exceptions.size()][]);
/*
* Choose a name for the proxy class to generate.
*/
final long num;
synchronized (nextUniqueNumberLock) {
num = nextUniqueNumber++;
}
String proxyName = proxyPkg + proxyClassNamePrefix + num;
proxyClass = generateProxy(proxyName, interfaces, loader, methodsArray,
exceptionsArray);
}
// add to set of all generated proxy classes, for isProxyClass
proxyClasses.put(proxyClass, null);
} finally {
/*
* We must clean up the "pending generation" state of the proxy
* class cache entry somehow. If a proxy class was successfully
* generated, store it in the cache (with a weak reference);
* otherwise, remove the reserved entry. In all cases, notify
* all waiters on reserved entries in this cache.
*/
synchronized (cache) {
if (proxyClass != null) {
cache.put(key, new WeakReference<Class<?>>(proxyClass));
} else {
cache.remove(key);
}
cache.notifyAll();
}
}
return proxyClass;
}
扩展阅读:
来自IBM的 Java 动态代理机制分析及扩展,第 1 部分
网友评论