1、我们先编写一个jdk的动态代理的一个demo
我们先创建一个抽象角色:
/**
* 抽象角色接口
* */
public interface AbstractRole {
/**
* 完成相关业务
* */
void process();
}
真实角色,被代理对象代理的类
/**
* 真实角色
* 需要被代理的目标对象
* */
public class RealRole implements AbstractRole{
@Override
public void process() {
System.out.println("完成用户的需求!");
}
}
然后写一个类,用于创建代理类,并且提供调用真实角色的方法。
/**
* JDK的动态代理
* */
public class ProxyRole implements InvocationHandler{
/**
* 被代理的目标对象
* */
private Object target;
/**
* 获得代理对象
* 参数:
* 1、类加载器
* 2、接口集合
* 3、h the invocation handler to dispatch method invocations to
* */
public Object getProxy(){
Object newProxyInstance = Proxy.newProxyInstance(ProxyRole.class.getClassLoader(), target.getClass().getInterfaces(), this);
return newProxyInstance;
}
/**
* 调用目标方法
* 集中处理动态代理类上的所有方法的调用。
* 调用处理器根据着三个参数进行预处理或分派到委托类实例上反射执行。
* */
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
//在代理真是对象前我们可以添加一些自己的操作
System.out.println("调用之前的操作!调用的方法:"+method.getName());
//调用目标方法
Object invoke = method.invoke(target, args);
//调用之后的操作
System.out.println("调用之后我的操作!");
//返回调用方法的返回值
return invoke;
}
public Object getTarget() {
return target;
}
public void setTarget(Object target) {
this.target = target;
}
}
然后写一个测试类:
/**
* JDK的动态代理,测试类
* */
public class JDKProxyTest {
public static void main(String[] args) {
//构建一个真实角色
RealRole role = new RealRole();
ProxyRole pr = new ProxyRole();
//设置真实角色,将这个真实角色让代理对象去代理他
pr.setTarget(role);
//创建代理对象
AbstractRole proxy = (AbstractRole) pr.getProxy();
//调用目标方法
proxy.process();
}
}
运行结果:
调用之前的操作!调用的方法:process
完成用户的需求!
调用之后我的操作!
源码解析:
我们追踪一下源码
public Object getProxy(){
Object newProxyInstance = Proxy.newProxyInstance(ProxyRole.class.getClassLoader(), target.getClass().getInterfaces(), this);
return newProxyInstance;
}
通过
Proxy.newProxyInstance(ProxyRole.class.getClassLoader(), target.getClass().getInterfaces(), this);
这个方法进去:
public static Object newProxyInstance(ClassLoader loader,
Class<?>[] interfaces,
InvocationHandler h)
throws IllegalArgumentException
{
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对象,由此可知,我们的代理类是通过调用此方法生成的
*/
Class<?> cl = getProxyClass0(loader, intfs);
/*
* Invoke its constructor with the designated invocation handler.
*/
try {
if (sm != null) {
checkNewProxyPermission(Reflection.getCallerClass(), cl);
}
//根据代理对象的class对象获得构造器
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);
}
}
有以上源码可知,生成代理对象的关键在于:
Class<?> cl = getProxyClass0(loader, intfs);
我们继续追踪源码:
/**
* 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);
}
然后我们继续追踪
proxyClassCache.get(loader, interfaces)
//这个方法就是通过缓存查找值
public V get(K key, P parameter) {
Objects.requireNonNull(parameter);
expungeStaleEntries();
Object cacheKey = CacheKey.valueOf(key, refQueue);
// lazily install the 2nd level valuesMap for the particular cacheKey
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;
}
}
// create subKey and retrieve the possible Supplier<V> stored by that
// subKey from valuesMap
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);
}
}
}
}
看源码的时候,抛掉一些if – else 等等判断和一些异常处理等不必要的逻辑,这样看源码就轻松很多了。
然后我们继续追踪:
// create subKey and retrieve the possible Supplier<V> stored by that
// subKey from valuesMap
Object subKey = Objects.requireNonNull(subKeyFactory.apply(key, parameter));
找到这个apply方法:
@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
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数组。
*/
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());
}
}
}
由此,我们知道代理对象的字节码对象就是通过这个方法生成的。
byte[] proxyClassFile = ProxyGenerator.generateProxyClass(
proxyName, interfaces, accessFlags);
追踪到这儿我们的任务差不多就结束了。
然后我们用一下generateProxyClass这个方法去生成字节码文件。
public static void getProxyClass() {
String proxyName = "proxy";
// 生成了代理类的字节码
byte[] proxyClassFile = ProxyGenerator.generateProxyClass(proxyName, RealRole.class.getInterfaces());
try {
fos = new FileOutputStream(proxyName + ".class");
fos.write(proxyClassFile);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
try {
fos.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
其实,这个方法生成的字节码文件,通过反编译之后,他其实调用的是invoke这个方法。
super.h.invoke(this, m3, null);
反编译之后的代理对象
public final class proxy1 extends Proxy
implements AbstractRole
{
private static Method m1;
private static Method m2;
private static Method m0;
private static Method m3;
public proxy1(InvocationHandler paramInvocationHandler)
throws
{
super(paramInvocationHandler);
}
对应的方法。
public final void process()
{
try
{
// 实际上就是调用MyInvocationHandler的public Object invoke(Object proxy, Method method, Object[] args)方法,第二个问题就解决了
super.h.invoke(this, m3, null);
return;
}
catch(Error _ex) { }
catch(Throwable throwable)
{
throw new UndeclaredThrowableException(throwable);
}
}