/**
* @author 郑小康
* 采用spi创建对应实例DelegatorFactoryImpl
* */
public static <A, R> R getObjectFromFactory(Class<? extends Factory<R, A>> factoryInterface, A obj) throws ClassNotFoundException {
Iterator<? extends Factory<R, A>> it = ServiceLoader.load(factoryInterface).iterator();
while (it.hasNext()) {
Factory<R, A> factory = it.next();
R instance = factory.getInstance(obj);
if (instance != null) {
return instance;
}
}
throw new ClassNotFoundException(factoryInterface.getClass().getName());
}
注:上下代码不是在一个类
/**
* @author 郑小康
* 根据delegatorName创建一个GenericDelegator
* 所以实际delegator引用的是一个GenericDelegator实例
* */
public class DelegatorFactoryImpl extends DelegatorFactory {
public static final String module = DelegatorFactoryImpl.class.getName();
public Delegator getInstance(String delegatorName) {
if (Debug.infoOn()) Debug.logInfo("Creating new delegator [" + delegatorName + "] (" + Thread.currentThread().getName() + ")", module);
//Debug.logInfo(new Exception(), "Showing stack where new delegator is being created...", module);
try {
return new GenericDelegator(delegatorName);
} catch (GenericEntityException e) {
Debug.logError(e, "Error creating delegator", module);
return null;
}
}
}