publicstatic Object newProxyInstance(ClassLoader loader,
Class>[] interfaces,
InvocationHandler h)
throws IllegalArgumentException
{
Objects.requireNonNull(h);
// Interfacefinal Class>[] intfs = interfaces.clone();
// Android-changed: sm is always null// final SecurityManager sm = System.getSecurityManager();// if (sm != null) {// checkProxyAccess(Reflection.getCallerClass(), loader, intfs);// }/*
* Look up or generate the designated proxy class.
* ClassLoader、Interface
* ------>
*/
Class> cl = getProxyClass0(loader, intfs);
/*
* Invoke its constructor with the designated invocation handler.
*/try {
// Android-changed: sm is always null// if (sm != null) {// checkNewProxyPermission(Reflection.getCallerClass(), cl);// }// // final Constructor> cons = cl.getConstructor(constructorParams);
final InvocationHandler ih = h;
// public if (!Modifier.isPublic(cl.getModifiers())) {
// Android-changed: Removed AccessController.doPrivileged
cons.setAccessible(true);
}
// return cons.newInstance(new Object[]{h});
} catch (IllegalAccessException|InstantiationException e) {
thrownew InternalError(e.toString(), e);
} catch (InvocationTargetException e) {
Throwable t = e.getCause();
if (t instanceof RuntimeException) {
throw (RuntimeException) t;
} else {
thrownew InternalError(t.toString(), t);
}
} catch (NoSuchMethodException e) {
thrownew InternalError(e.toString(), e);
}
}
getProxyClass 0ソース分析
Class
privatestatic Class> getProxyClass0(ClassLoader loader,
Class>... interfaces) {
// 65535 , , if (interfaces.length > 65535) {
thrownew 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 ProxyClassFactoryreturn proxyClassCache.get(loader, interfaces);
}
proxyClassCache分析
new KeyFactory()とnew ProxyClassFactory()の2つのオブジェクトは、すべてのエージェントクラスのマッピングを処理します.
/**
* a cache of proxy classes
*
* :new KeyFactory()、new ProxyClassFactory() ,
*/privatestaticfinal WeakCache[], Class>>
proxyClassCache = new WeakCache<>(new KeyFactory(), new ProxyClassFactory());
/**
* WeakCache.get(loader, interfaces)
*/public V get(K key, P parameter) {
Objects.requireNonNull(parameter);
expungeStaleEntries();
Object cacheKey = CacheKey.valueOf(key, refQueue);
// key(ClassLoader) , CacheKey Factory // lazily install the 2nd level valuesMap for the particular cacheKey
ConcurrentMap
Factoryソース分析
Factoryによるプロキシオブジェクトの生成
privatefinalclassFactoryimplementsSupplier<V> {privatefinal K key;
privatefinal P parameter;
privatefinal Object subKey;
privatefinal 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) {
// something changed while we were waiting:// might be that we were replaced by a CacheValue// or were removed because of failure ->// return null to signal WeakCache.get() to retry// the loopreturnnull;
}
// else still us (supplier == this)// create new value
V value = null;
try {
// ValueFactory
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 Supplier hashcode equals , ,
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 {
thrownew AssertionError("Should not reach here");
}
// successfully replaced us with new CacheValue -> return the value// wrapped by itreturn value;
}
}
privatestaticfinalclassProxyClassFactoryimplementsBiFunction<ClassLoader, Class>[], Class>>
{// prefix for all proxy class namesprivatestaticfinal String proxyClassNamePrefix = "$Proxy";
// next number to use for generation of unique proxy class namesprivatestaticfinal AtomicLong nextUniqueNumber = new AtomicLong();
@Override
public Class> apply(ClassLoader loader, Class>[] interfaces) {
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) {
thrownew IllegalArgumentException(
intf + " is not visible from class loader");
}
/*
* Verify that the Class object actually represents an
* interface.
*/// , // java if (!interfaceClass.isInterface()) {
thrownew IllegalArgumentException(
interfaceClass.getName() + " is not an interface");
}
/*
* Verify that this interface is not a duplicate.
*/if (interfaceSet.put(interfaceClass, Boolean.TRUE) != null) {
thrownew IllegalArgumentException(
"repeated interface: " + interfaceClass.getName());
}
}
String proxyPkg = null; // package to define proxy class inint 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();
// interface public// public , + $Proxy1if (!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;
} elseif (!pkg.equals(proxyPkg)) {
thrownew IllegalArgumentException(
"non-public interfaces from different packages");
}
}
}
if (proxyPkg == null) {
// if no non-public proxy interfaces, use the default package.
proxyPkg = "";
}
// java ,java com.sun.proxy$Proxy1, Android $Proxy1
{
// Android-changed: Generate the proxy directly instead of calling// through to ProxyGenerator.
List methods = getMethods(interfaces);
Collections.sort(methods, ORDER_BY_SIGNATURE_AND_SUBTYPE);
validateReturnTypes(methods);
List[]> 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.
*/// $Proxy , 1// nextUniqueNumber 1, long num = nextUniqueNumber.getAndIncrement();
String proxyName = proxyPkg + proxyClassNamePrefix + num;
// , native return generateProxy(proxyName, interfaces, loader, methodsArray,
exceptionsArray);
}
}
}