java.util.ServiceLoader.iterator()方法的使用及代码示例

x33g5p2x  于2022-01-29 转载在 其他  
字(8.5k)|赞(0)|评价(0)|浏览(145)

本文整理了Java中java.util.ServiceLoader.iterator()方法的一些代码示例,展示了ServiceLoader.iterator()的具体用法。这些代码示例主要来源于Github/Stackoverflow/Maven等平台,是从一些精选项目中提取出来的代码,具有较强的参考意义,能在一定程度帮忙到你。ServiceLoader.iterator()方法的具体详情如下:
包路径:java.util.ServiceLoader
类名称:ServiceLoader
方法名:iterator

ServiceLoader.iterator介绍

[英]Returns an iterator over all the service providers offered by this service loader. Note that hasNext and next may throw if the configuration is invalid.

Each iterator will return new instances of the classes it iterates over, so callers may want to cache the results of a single call to this method rather than call it repeatedly.

The returned iterator does not support remove.
[中]返回此服务加载程序提供的所有服务提供程序的迭代器。请注意,如果配置无效,hasNext和next可能会抛出。
每个迭代器将返回其迭代的类的新实例,因此调用方可能希望缓存对该方法的单个调用的结果,而不是重复调用它。
返回的迭代器不支持删除。

代码示例

代码示例来源:origin: ctripcorp/apollo

public static <S> Iterator<S> loadAll(Class<S> clazz) {
  ServiceLoader<S> loader = ServiceLoader.load(clazz);

  return loader.iterator();
 }
}

代码示例来源:origin: swagger-api/swagger-core

@Override
  public boolean exists(String path) {

    try {
      ServiceLoader<OpenAPIConfigBuilder> loader = ServiceLoader.load(OpenAPIConfigBuilder.class);
      if (loader.iterator().hasNext()) {
        loader.iterator().next();
        return true;
      }
      return false;
    } catch (Exception e) {
      return false;
    }
  }
}

代码示例来源:origin: spring-projects/spring-framework

@Override
protected Object getObjectToExpose(ServiceLoader<?> serviceLoader) {
  Iterator<?> it = serviceLoader.iterator();
  if (!it.hasNext()) {
    throw new IllegalStateException(
        "ServiceLoader could not find service for type [" + getServiceType() + "]");
  }
  return it.next();
}

代码示例来源:origin: eclipse-vertx/vert.x

public static <T> Collection<T> loadFactories(Class<T> clazz, ClassLoader classLoader) {
  List<T> list = new ArrayList<>();
  ServiceLoader<T> factories;
  if (classLoader != null) {
   factories = ServiceLoader.load(clazz, classLoader);
  } else {
   // this is equivalent to:
   // ServiceLoader.load(clazz, TCCL);
   factories = ServiceLoader.load(clazz);
  }
  if (factories.iterator().hasNext()) {
   factories.iterator().forEachRemaining(list::add);
   return list;
  } else {
   // By default ServiceLoader.load uses the TCCL, this may not be enough in environment dealing with
   // classloaders differently such as OSGi. So we should try to use the  classloader having loaded this
   // class. In OSGi it would be the bundle exposing vert.x and so have access to all its classes.
   factories = ServiceLoader.load(clazz, ServiceHelper.class.getClassLoader());
   if (factories.iterator().hasNext()) {
    factories.iterator().forEachRemaining(list::add);
    return list;
   } else {
    return Collections.emptyList();
   }
  }
 }
}

代码示例来源:origin: gocd/gocd

private IVProvider getIvProviderInstance() {
  if (ivProvider == null) {
    synchronized (AESEncrypter.class) {
      if (ivProvider == null) {
        ivProvider = ServiceLoader.load(IVProvider.class).iterator().next();
      }
    }
  }
  return ivProvider;
}

代码示例来源:origin: jenkinsci/jenkins

/**
 * Obtains the instance to be used.
 */
public static InitStrategy get(ClassLoader cl) throws IOException {
  Iterator<InitStrategy> it = ServiceLoader.load(InitStrategy.class, cl).iterator();
  if (!it.hasNext()) {
    return new InitStrategy(); // default
  }
  InitStrategy s = it.next();
  LOGGER.log(Level.FINE, "Using {0} as InitStrategy", s);
  return s;
}

代码示例来源:origin: org.springframework/spring-beans

@Override
protected Object getObjectToExpose(ServiceLoader<?> serviceLoader) {
  Iterator<?> it = serviceLoader.iterator();
  if (!it.hasNext()) {
    throw new IllegalStateException(
        "ServiceLoader could not find service for type [" + getServiceType() + "]");
  }
  return it.next();
}

代码示例来源:origin: javax.enterprise/cdi-api

private static void findAllProviders() {
  ServiceLoader<CDIProvider> providerLoader;
  Set<CDIProvider> providers = new TreeSet<>(Comparator.comparingInt(CDIProvider::getPriority).reversed());
  providerLoader = ServiceLoader.load(CDIProvider.class, CDI.class.getClassLoader());
  if(! providerLoader.iterator().hasNext()) {
    throw new IllegalStateException("Unable to locate CDIProvider");
  }
  try {
    providerLoader.forEach(providers::add);
  } catch (ServiceConfigurationError e) {
    throw new IllegalStateException(e);
  }
  CDI.discoveredProviders = Collections.unmodifiableSet(providers);
}

代码示例来源:origin: apache/rocketmq

if (messageStore.getMessageStoreConfig().isTransientStorePoolEnable()) {
  try {
    mappedFile = ServiceLoader.load(MappedFile.class).iterator().next();
    mappedFile.init(req.getFilePath(), req.getFileSize(), messageStore.getTransientStorePool());
  } catch (RuntimeException e) {

代码示例来源:origin: SonarSource/sonarqube

Set<CoreExtension> load(ClassLoader classLoader) {
  ServiceLoader<CoreExtension> loader = ServiceLoader.load(CoreExtension.class, classLoader);
  return ImmutableSet.copyOf(loader.iterator());
 }
}

代码示例来源:origin: ch.qos.logback/logback-classic

public static <T> T loadFromServiceLoader(Class<T> c) {
  ServiceLoader<T> loader = ServiceLoader.load(c, getServiceLoaderClassLoader());
  Iterator<T> it = loader.iterator();
  if (it.hasNext())
    return it.next();
  return null;
}

代码示例来源:origin: yu199195/Raincat

public static <S> S loadFirst(final Class<S> clazz) {
  final ServiceLoader<S> loader = loadAll(clazz);
  final Iterator<S> iterator = loader.iterator();
  if (!iterator.hasNext()) {
    throw new IllegalStateException(String.format(
        "No implementation defined in /META-INF/services/%s, please check whether the file exists and has the right implementation class!",
        clazz.getName()));
  }
  return iterator.next();
}

代码示例来源:origin: spring-projects/spring-framework

@Test
public void testServiceListFactoryBean() {
  assumeTrue(ServiceLoader.load(DocumentBuilderFactory.class).iterator().hasNext());
  DefaultListableBeanFactory bf = new DefaultListableBeanFactory();
  RootBeanDefinition bd = new RootBeanDefinition(ServiceListFactoryBean.class);
  bd.getPropertyValues().add("serviceType", DocumentBuilderFactory.class.getName());
  bf.registerBeanDefinition("service", bd);
  List<?> serviceList = (List<?>) bf.getBean("service");
  assertTrue(serviceList.get(0) instanceof DocumentBuilderFactory);
}

代码示例来源:origin: org.apache.commons/commons-compress

public ServiceLoaderIterator(final Class<E> service, final ClassLoader classLoader) {
  this.service = service;
  final ServiceLoader<E> serviceLoader = ServiceLoader.load(service, classLoader);
  serviceLoaderIterator = serviceLoader.iterator();
  nextServiceLoader = null;
}

代码示例来源:origin: swagger-api/swagger-core

@Override
public OpenAPIConfiguration load(String path) throws IOException {
  ServiceLoader<OpenAPIConfigBuilder> loader = ServiceLoader.load(OpenAPIConfigBuilder.class);
  if (loader.iterator().hasNext()) {
    return loader.iterator().next().build();
  }
  throw new IOException("Error loading OpenAPIConfigBuilder service implementation.");
}

代码示例来源:origin: alibaba/nacos

private void initCmdbService() throws NacosException {
  Iterator<CmdbService> iterator = serviceLoader.iterator();
  if (iterator.hasNext()) {
    cmdbService = iterator.next();
  }
  if (cmdbService == null && switches.isLoadDataAtStart()) {
    throw new NacosException(NacosException.SERVER_ERROR, "Cannot initialize CmdbService!");
  }
}

代码示例来源:origin: spring-projects/spring-framework

@Test
public void testServiceFactoryBean() {
  assumeTrue(ServiceLoader.load(DocumentBuilderFactory.class).iterator().hasNext());
  DefaultListableBeanFactory bf = new DefaultListableBeanFactory();
  RootBeanDefinition bd = new RootBeanDefinition(ServiceFactoryBean.class);
  bd.getPropertyValues().add("serviceType", DocumentBuilderFactory.class.getName());
  bf.registerBeanDefinition("service", bd);
  assertTrue(bf.getBean("service") instanceof DocumentBuilderFactory);
}

代码示例来源:origin: neo4j/neo4j

/**
   * @return instances of all classes with loadable configuration options
   */
  static List<LoadableConfig> allConfigClasses()
  {
    return Iterators.stream( ServiceLoader.load( LoadableConfig.class ).iterator() ).collect( Collectors.toList() );
  }
}

代码示例来源:origin: org.assertj/assertj-core

public static <SERVICE> SERVICE get(Class<SERVICE> serviceType, SERVICE defaultValue) {

  Iterator<SERVICE> services = ServiceLoader.load(serviceType, Services.class.getClassLoader()).iterator();

  SERVICE result = services.hasNext() ? services.next() : defaultValue;
  if (services.hasNext()) {
   result = defaultValue;
   System.err.println(format("Found multiple implementations for the service provider %s. Using the default: %s",
                serviceType, result.getClass()));
  }
  return result;
 }
}

代码示例来源:origin: yu199195/hmily

/**
 * Load first s.
 *
 * @param <S>   the type parameter
 * @param clazz the clazz
 * @return the s
 */
public static <S> S loadFirst(final Class<S> clazz) {
  final ServiceLoader<S> loader = loadAll(clazz);
  final Iterator<S> iterator = loader.iterator();
  if (!iterator.hasNext()) {
    throw new IllegalStateException(String.format(
        "No implementation defined in /META-INF/services/%s, please check whether the file exists and has the right implementation class!",
        clazz.getName()));
  }
  return iterator.next();
}

相关文章