怎麼是這樣的:
private static Map<String, Object> cache =
new ConcurrentHashMap<String, Object>();
@SuppressWarnings("unchecked")
public static <T> T getImplementation(final String implementationClass){
T result;
synchronized(cache){
result = (T) cache.get(implementationClass);
if(result == null){
try{
result =
(T) Class.forName(implementationClass).newInstance();
} catch(final Exception e){
// error handling here
}
cache.put(implementationClass, result);
}
}
return result;
}
這將保證各只有一個類的實例被使用(只要你只能使用此方法)
實例應用:
FooService service = getImplementation("com.mycompany.FooServiceImpl");
使用Guava ,這個代碼可以改善with a Computing Map:
private static Map<String, Object> cache =
new MapMaker().makeComputingMap(
new Function<String, Object>(){
@Override
public Object apply(final String input){
try{
return Class.forName(input).newInstance();
} catch(final Exception e){
// error handling here
}
}
});
@SuppressWarnings("unchecked")
public static <T> T getImplementation(final String implementationClass){
return (T) cache.get(implementationClass);
}
或者反過來說:由不同的類加載器加載的相同字節碼導致不同的類(具有單獨的靜態特性)。 – 2011-03-17 12:43:27