类加载器:ServiceLoader简述

  1. e();  
  2. }  
(2)具体服务实现1:HDFSService

[java]  view plain  copy
  1. package com.impl;  
  2.   
  3. import com.service.IService;  
  4.   
  5. public class HDFSService implements IService {  
  6.   
  7.     @Override  
  8.   
  9.     public String sayHello() {  
  10.   
  11.         return "Hello HDFSService";  
  12.   
  13.     }  
  14.   
  15.     @Override  
  16.   
  17.     public String getScheme() {  
  18.   
  19.         return "hdfs";  
  20.   
  21.     }  
  22. }  
(3) 具体服务实现2:LocalService

[java]  view plain  copy
  1. package com.impl;  
  2.   
  3. import com.service.IService;  
  4.   
  5. public class LocalService  implements IService {  
  6.   
  7.     @Override  
  8.   
  9.     public String sayHello() {  
  10.   
  11.         return "Hello LocalService";  
  12.   
  13.     }  
  14.   
  15.     @Override  
  16.   
  17.     public String getScheme() {  
  18.   
  19.         return "local";  
  20.   
  21.     }  
  22. }  
(4)配置:META-INF/services/com.service.IService

[java]  view plain  copy
  1. com.impl.HDFSService  
  2. com.impl.LocalService  
(5)测试类

[java]  view plain  copy
  1. package com.test;  
  2.   
  3. import java.util.ServiceLoader;  
  4.   
  5. import com.service.IService;  
  6.   
  7. public class Test {  
  8.   
  9.     public static void main(String[] args) {  
  10.   
  11.         ServiceLoader<IService> serviceLoader  = ServiceLoader.load(IService.class);  
  12.   
  13.         for (IService service : serviceLoader) {  
  14.   
  15.             System.out.println(service.getScheme()+"="+service.sayHello());  
  16.   
  17.         }  
  18.   
  19.     }  
  20. }  

结果:

hdfs=Hello HDFSService
local=Hello LocalService

可以看到ServiceLoader可以根据IService把定义的两个实现类找出来,返回一个ServiceLoader的实现,而ServiceLoader实现了Iterable接口,所以可以通过ServiceLoader来遍历所有在配置文件中定义的类的实例

猜你喜欢

转载自blog.csdn.net/qq_34368762/article/details/79973551
今日推荐