Java.util.ServiceLoader.iterator() 方法
描述
java.util.ServiceLoader.iterator() 方法延迟加载此加载器服务的可用提供程序。 此方法返回的迭代器首先按实例化顺序生成提供程序缓存的所有元素。 然后它会延迟加载并实例化任何剩余的提供者,依次将每个提供者添加到缓存中。
声明
以下是 java.util.ServiceLoader.iterator() 方法的声明
public Iterator<S> iterator()
参数
NA
返回值
此方法返回一个迭代器,该迭代器会延迟加载此加载器服务的提供程序
异常
NA
示例
为了注册服务,我们的类路径中需要一个 META-INF/service 文件夹。 在这个特定的文件夹中,我们需要一个文本文件,其中包含我们实现的接口的名称,其中包含一行列出实现的具体类名称。 在我们的例子中,文件的名称是 com.tutorialspoint.ServiceProvider 并包含这一行 −
com.tutorialspoint.ServiceImplementation
Our service code is the following −
package com.tutorialspoint;
public class ServiceImplementation extends ServiceProvider {
public String getMessage() {
return "Hello World";
}
}
以下代码加载注册的服务并使用它从服务中获取消息 −
package com.tutorialspoint;
import java.util.Iterator;
import java.util.ServiceLoader;
public abstract class ServiceProvider {
public static ServiceProvider getDefault() {
// load our plugin
ServiceLoader<ServiceProvider> serviceLoader =
ServiceLoader.load(ServiceProvider.class);
// load the available providers of this loader's service.
Iterator<ServiceProvider> iterator = serviceLoader.iterator();
// check if there is a provider
System.out.println("Iterator has more provider:" + iterator.hasNext());
// use the provider to get the message
System.out.println("" + iterator.next().getMessage());
// checking if load was successful
for (ServiceProvider provider : serviceLoader) {
return provider;
}
throw new Error("Something is wrong with registering the addon");
}
public abstract String getMessage();
public static void main(String[] ignored) {
// create a new provider and call getMessage()
ServiceProvider provider = ServiceProvider.getDefault();
System.out.println(provider.getMessage());
}
}
让我们编译并运行上面的程序,这将产生以下结果 −
Iterator has more providers:true Hello World Hello World

