zoukankan      html  css  js  c++  java
  • 聊聊、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();
    }
    }

     

     

     

  • 相关阅读:
    【WPF】Blend for Visual Studio 2013 入门
    【c#】获取CPU序列号及遇到的问题
    【GIT】学习笔记
    【备份】一些留待学习的好网站
    【VS】无法折叠所有方法的问题 VS2013
    【概念】XML
    配置JDK
    TCP/IP Wireshark监听 及错误代码
    软件比较
    湖南省专升本
  • 原文地址:https://www.cnblogs.com/xums/p/10398467.html
Copyright © 2011-2022 走看看