代码示例
public class SomeClass {
public String sayHi() {
return "hi";
}
}
public class SomeClassDoSomething {
public static void main(String[] args) {
S s = new S() {
public String sayHi() {
return "hello";
}
};
System.out.println(s.sayHi());
// print:hello
}
}
结合泛型使用更加经典!
org.apache.commons.beanutils.ContextClassLoaderLocal<T>
这个类的使用就用到了上述的技巧。
public class BeanUtilsBean {
/**
* Contains <code>BeanUtilsBean</code> instances indexed by context classloader.
*/
//这里new了ContextClassLoaderLocal这个类,然后使用内部类的方式重写了`initialValue()`初始化方法
private static final ContextClassLoaderLocal<BeanUtilsBean>
BEANS_BY_CLASSLOADER = new ContextClassLoaderLocal<BeanUtilsBean>() {
// Creates the default instance used when the context classloader is unavailable
@Override
protected BeanUtilsBean initialValue() {
return new BeanUtilsBean();
}
};
/**
* Gets the instance which provides the functionality for {@link BeanUtils}.
* This is a pseudo-singleton - an single instance is provided per (thread) context classloader.
* This mechanism provides isolation for web apps deployed in the same container.
*
* @return The (pseudo-singleton) BeanUtils bean instance
*/
public static BeanUtilsBean getInstance() {
return BEANS_BY_CLASSLOADER.get();//调用`ContextClassLoaderLocal`的`get()`方法,往下看👇
}
//...... 其余代码省略
}
public class ContextClassLoaderLocal<T> {
private final Map<ClassLoader, T> valueByClassLoader = new WeakHashMap<ClassLoader, T>();
private boolean globalValueInitialized = false;
private T globalValue;
/**
* Construct a context classloader instance
*/
public ContextClassLoaderLocal() {
super();
}
//使用时若没有重写这个方法,返回的是null
protected T initialValue() {
return null;
}
public synchronized T get() {
valueByClassLoader.isEmpty();
try {
final ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader();
if (contextClassLoader != null) {
T value = valueByClassLoader.get(contextClassLoader);
if ((value == null)
&& !valueByClassLoader.containsKey(contextClassLoader)) {
value = initialValue();
valueByClassLoader.put(contextClassLoader, value);
}
return value;
}
} catch (final SecurityException e) { /* SWALLOW - should we log this? */ }
// if none or exception, return the globalValue
if (!globalValueInitialized) {
globalValue = initialValue();
globalValueInitialized = true;
}//else already set
return globalValue;
}
// ... ... 其余代码省略
}