聊聊、Java SPI

SPI,Service Provider Interface,服务提供者接口。

Animal 接口


 package com.rockcode.www.spi;

 public interface Animal {

 void speek();

}

Dog 类


 package com.rockcode.www.spi;

 public class Dog implements Animal {

 public void speek() {

System.out.println("....Dog....");
}

 }

SPI规范


 

com.rockcode.www.spi.Animal 文件内容 com.rockcode.www.spi.Dog

注意,文件必须位于 Jar 包的 META-INF/services 下面,名称与接口名相同

ServiceLoader


 

ServiceLoader<Animal> loader = ServiceLoader.load(Animal.class);
for (Animal an : loader) {
an.speek();
}

 

源码


 

URL url = ClassLoader.getSystemClassLoader().getResource(
"META-INF/services/" + Animal.class.getName());
InputStream ins = null;
BufferedReader br = null;
try {
ins = url.openStream();
br = new BufferedReader(new InputStreamReader(ins));

 

String ln = br.readLine();
System.out.println(ln);

 

try {
Class<?> c = Class.forName(ln);
try {
Object o = c.newInstance();
Dog d = (Dog) c.cast(o);
d.speek();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
}

 

} catch (IOException e) {
e.printStackTrace();
} finally {
if (br != null)
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
if (ins != null)
try {
ins.close();
} catch (IOException e) {
e.printStackTrace();
}
}

 

 

 

原文地址:https://www.cnblogs.com/xums/p/10398467.html