聊聊、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
總結
以上是生活随笔為你收集整理的聊聊、Java SPI的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Java——重载和重写
- 下一篇: mui框架提供的相关api