All Downloads are FREE. Search and download functionalities are using the official Maven repository.

io.scalecube.utils.ServiceLoaderUtil Maven / Gradle / Ivy

The newest version!
package io.scalecube.utils;

import java.util.Optional;
import java.util.ServiceLoader;
import java.util.function.Predicate;
import java.util.stream.Stream;
import java.util.stream.StreamSupport;

public final class ServiceLoaderUtil {

  private ServiceLoaderUtil() {
    // Do not instantiate
  }

  /**
   * Finds the first implementation of the given service type and creates its instance.
   *
   * @param clazz service type
   * @return the first implementation of the given service type
   */
  public static  Optional findFirst(Class clazz) {
    ServiceLoader load = ServiceLoader.load(clazz);
    return StreamSupport.stream(load.spliterator(), false).findFirst();
  }

  /**
   * Finds the first implementation of the given service type using the given predicate to filter
   * out found service types and creates its instance.
   *
   * @param clazz service type
   * @param predicate service type predicate
   * @return the first implementation of the given service type
   */
  public static  Optional findFirst(Class clazz, Predicate predicate) {
    ServiceLoader load = ServiceLoader.load(clazz);
    Stream stream = StreamSupport.stream(load.spliterator(), false);
    return stream.filter(predicate).findFirst();
  }

  /**
   * Finds all implementations of the given service type and creates their instances.
   *
   * @param clazz service type
   * @return implementations' stream of the given service type
   */
  public static  Stream findAll(Class clazz) {
    ServiceLoader load = ServiceLoader.load(clazz);
    return StreamSupport.stream(load.spliterator(), false);
  }

  /**
   * Finds all implementations of the given service type using the given predicate to filter out
   * found service types and creates their instances.
   *
   * @param clazz service type
   * @param predicate service type predicate
   * @return implementations' stream of the given service type
   */
  public static  Stream findAll(Class clazz, Predicate predicate) {
    ServiceLoader load = ServiceLoader.load(clazz);
    return StreamSupport.stream(load.spliterator(), false).filter(predicate);
  }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy