日韩av黄I国产麻豆传媒I国产91av视频在线观看I日韩一区二区三区在线看I美女国产在线I麻豆视频国产在线观看I成人黄色短片

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 >

聊聊、Java SPI

發布時間:2025/4/14 39 豆豆
生活随笔 收集整理的這篇文章主要介紹了 聊聊、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的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。