public interface BusinessInterface
{
public void doSomething();
public void doSomething2();
public void doSomething3(String input);
}
实现类:
public class BusinessClass implements BusinessInterface
{
public static final String TAG = "BfdUtils";
public void doSomething()
{
System.out.println("业务组件BusinessClass方法调用:doSomething()");
doSomething2();// 在这里调用不会被拦截
}
public void doSomething2()
{
System.out.println("业务组件BusinessClass方法调用:doSomething()=====" + TAG);
}
@Override
public void doSomething3(String input)
{
System.out.println(input);
}
}
public class Client
{
public static void main(String args[])
{
DynamicProxyHandler handler = new DynamicProxyHandler();
BusinessInterface business = new BusinessClass();
BusinessInterface businessProxy = handler.bind(business);
businessProxy.doSomething();//只有直接执行businessProxy的方法才会被拦截
System.out.println("===========================");
BusinessInterface2 business2 = new BusinessClass2();
BusinessInterface2 businessProxy2 = handler.bind(business2);
businessProxy2.doSomething();
}
}
源码浅析
从Proxy.newProxyInstance开始
public class Proxy implements java.io.Serializable {
private static final long serialVersionUID = -2222568056686623797L;
// 生成的动态代理类在反射调用构造器实例化时需要知道构造方法的参数,前面讲过Proxy是分派方法给InvocationHandler去执行的,所有它持有一个InvocationHandler的引用。
private static final Class>[] constructorParams =
{ InvocationHandler.class };
/*
* @param type of keys
* @param
type of parameters
* @param type of values
*/
// 代理类缓存
private static final WeakCache[], Class>>
proxyClassCache = new WeakCache<>(new KeyFactory(), new ProxyClassFactory());
// 持有InvocationHandler实例引用
protected InvocationHandler h;
/**
* Prohibits instantiation.
*/
private Proxy() {
}
// 被子类调用,protected
protected Proxy(InvocationHandler h) {
Objects.requireNonNull(h);
this.h = h;
}
@CallerSensitive
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> cl = getProxyClass0(loader, intfs);
/*
* Invoke its constructor with the designated invocation handler.
*/
try {
if (sm != null) {
checkNewProxyPermission(Reflection.getCallerClass(), cl);
}
// 反射获取构造器(参数为InvocationHanlder那个构造器)
final Constructor> cons = cl.getConstructor(constructorParams);
final InvocationHandler ih = h;
if (!Modifier.isPublic(cl.getModifiers())) {
AccessController.doPrivileged(new PrivilegedAction() {
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);
}
}
private static Class> getProxyClass0(ClassLoader loader,
Class>... interfaces) {
// 限制被代理类实现的接口数65535
if (interfaces.length > 65535) {
throw new IllegalArgumentException("interface limit exceeded");
}
// 如果cache中找到了已经存在代理类,则直接返回,找不到再执行黑科技,下一节我们跳转到proxyClassCache的get方法里面去
return proxyClassCache.get(loader, interfaces);
}
}
proxyClassCache.get-生成代理类的黑科技
// 前面传进来的key为classloader, parameter为接口列表
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
WeakCache内部类Factory的get逻辑
private final class Factory implements Supplier {
private final K key;
private final P parameter;
private final Object subKey;
private final ConcurrentMap> valuesMap;
Factory(K key, P parameter, Object subKey,
ConcurrentMap> valuesMap) {
this.key = key;
this.parameter = parameter;
this.subKey = subKey;
this.valuesMap = valuesMap;
}
@Override
public synchronized V get() { // serialize access
// re-check
Supplier supplier = valuesMap.get(subKey);
if (supplier != this) {
// 这里出现诡异的情况直接返回null,因为上层调用者的到null结果时,会继续循环,参照上面那一段代码
return null;
}
// else still us (supplier == this)
// create new value
V value = null;
try {
// 这里是黑科技的真正入口, 调用了valueFactory这个bifcuntion,从Poxy类实例化WeakCcahe实例的代码可知,valueFactory为Proxy类的内部类ProxyClassFactory,下面进入Proxy内部类ProxyClassFactory
value = Objects.requireNonNull(valueFactory.apply(key, parameter));
} finally {
if (value == null) { // remove us on failure
valuesMap.remove(subKey, this);
}
}
// the only path to reach here is with non-null value
assert value != null;
// wrap value with CacheValue (WeakReference)
CacheValue cacheValue = new CacheValue<>(value);
// try replacing us with CacheValue (this should always succeed)
if (valuesMap.replace(subKey, this, cacheValue)) {
// put also in reverseMap
reverseMap.put(cacheValue, Boolean.TRUE);
} else {
throw new AssertionError("Should not reach here");
}
// successfully replaced us with new CacheValue -> return the value
// wrapped by it
return value;
}
}
private static final class ProxyClassFactory
implements BiFunction[], Class>>
{
// prefix for all proxy class names
// 可见代理类类名前缀都是$Proxy
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) {
// 这里用IdentityHashMap
Map, 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.
*/
// 决定生成的代理类放到哪个包下面,如果接口里有非公开接口(java的接口只有public和包级别两个访问级别),则与接口的包一致(前提是所有的包级别接口需要在同一个包下面),如果全部都是pubic的接口,则放到 com.sun.proxy包下面。
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.
*/
// 这里生成了代理类的二进制类文件, ProxyGenerator.generateProxyClass,在sun.misc包里面,没法看里面的代码。
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());
}
}
}
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml&q