net.gdface.utils.SPIUtils Maven / Gradle / Ivy
package net.gdface.utils;
import java.util.Iterator;
import java.util.ServiceLoader;
public class SPIUtils {
private SPIUtils() {
}
/**
* SPI(Service Provider Interface)机制加载接口实例实例,
* 没有找到返回默认实例
* @param interfaceClass 接口类
* @param defaultInstance
* @return T instance
*/
public static T loadProvider(Class interfaceClass,T defaultInstance) {
Assert.notNull(interfaceClass, "interfaceClass");
Iterator itor = serviceLoaderOf(interfaceClass).iterator();
if(!itor.hasNext()){
return defaultInstance;
}
return itor.next();
}
/**
* 优先调用{@link ServiceLoader#load(Class)},如果返回为空则调用{@link ServiceLoader#load(Class, ClassLoader)}
* @param
* @param service
* @since 2.8.6
*/
public static ServiceLoader serviceLoaderOf(Class service){
ServiceLoader loader = ServiceLoader.load(service);
return loader.iterator().hasNext() ? loader : ServiceLoader.load(service,service.getClassLoader());
}
}