类加载器特技:OSGi代码生成
2010-03-01 00:00:00 来源:WEB开发网...
/* Ask the app to resolve the target class */
Bundle app = ...
Class target = app.loadClass("com.acme.devices.SinisterEngine");
/* Get the defining classloader of the target */
ClassLoader targetSpace = target.getClassLoader();
/* Get the bridge for the class space of the target */
BridgeClassLoaderCache cache = ...
ClassLoader bridge = cache.resolveBridge(targetSpace);
桥缓存看起来会是这样:
public class BridgeClassLoaderCache {
private final ClassLoader primary;
private final Map<ClassLoader, WeakReference<ClassLoader>> cache;
public BridgeClassLoaderCache(ClassLoader primary) {
this.primary = primary;
this.cache = new WeakHashMap<ClassLoader, WeakReference<ClassLoader>>();
}
public synchronized ClassLoader resolveBridge(ClassLoader secondary) {
ClassLoader bridge = null;
WeakReference<ClassLoader> ref = cache.get(secondary);
if (ref != null) {
bridge = ref.get();
}
if (bridge == null) {
bridge = new BridgeClassLoader(primary, secondary);
cache.put(secondary, new WeakReference<ClassLoader>(bridge));
}
return bridge;
}
}
更多精彩
赞助商链接