ServiceLoader加载接口实现步骤
1.编写接口
public interface CommunicationAdapterFactory {void setKernel(LocalKernel kernel);boolean providesAdapterFor(Vehicle vehicle);BasicCommunicationAdapter getAdapterFor(Vehicle vehicle);
}
2.编写实现
// 实现类 1
public final class LoopbackCommunicationAdapterFactory implements CommunicationAdapterFactory {@Overridepublic void setKernel(LocalKernel kernel) {}@Overridepublic boolean providesAdapterFor(Vehicle vehicle) {return true;}@Overridepublic BasicCommunicationAdapter getAdapterFor(Vehicle vehicle) {return null;}
}// 实现类 2
public final class MqttCommunicationAdapterFactory implements CommunicationAdapterFactory {@Overridepublic void setKernel(LocalKernel kernel) {}@Overridepublic boolean providesAdapterFor(Vehicle vehicle) {return true;}@Overridepublic BasicCommunicationAdapter getAdapterFor(Vehicle vehicle) {return null;}
}
3.要在resources文件夹下创建文件夹 “META-INF/services”
在创建的文件夹下,将接口文件的引用作为文件名创建文件
4.将实现的接口文件引用作为文件内容放到文件中
com.mj.tcs.adapter.mqtt.MqttCommunicationAdapterFactory
5.实现加载
public static void main(String[] args) {ServiceLoader<CommunicationAdapterFactory> factoryLoader = ServiceLoader.load(CommunicationAdapterFactory.class);for (CommunicationAdapterFactory factory : factoryLoader) {System.out.println(factory);}}