ServiceLoader类:
使用过程:
public static void main(String[] args){
// 找到实现driver接口的数据库厂商的实现类
// ServiceLoader:此方法先由系统类加载器来尝试加载,由双亲委托模型,此方法尝试使用boot
// 加载器来加载,根加载器可以成功加载。如果不使用ServiceLoader.load,则尝试使用boot来加载
// Driver,而Driver在classpath路径下,不能由boot加载,加载失败
ServiceLoader<Driver> loader = ServiceLoader.load(Driver.class);
Iterator<Driver> iterator = loader.iterator();
//遵循SPI规范,去特定的目录寻找特定的文件然后解析出文件里的每一行,并且把每一行的信息读取出来,在
//需要的时候进行加载
while (iterator.hasNext()){
Driver driver = iterator.next();
System.out.println("driver: " + driver.getClass()
+ ", loader: " + driver.getClass().getClassLoader());
}
System.out.println("CurrentThreadClassLoader : " + Thread.currentThread().getContextClas