java.util.ServiceLoader Maven / Gradle / Ivy
The newest version!
package java.util;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Optional;
import jsinterop.annotations.JsFunction;
public final class ServiceLoader implements Iterable {
private static final Map, ?>> JS_SERVICE_PROVIDERS =
new HashMap<>();
private final Class service;
private final Map, S> implementations;
@FunctionalInterface
@JsFunction
public static interface ServiceProvider {
T provideService();
}
private ServiceLoader(Class service, Map, S> implementations) {
this.service = service;
this.implementations = implementations;
}
@Override
public Iterator iterator() {
if (implementations == null) {
return Collections.emptyIterator();
} else {
final Iterator, S>> it = implementations.entrySet().iterator();
return new Iterator() {
@Override
public boolean hasNext() {
return it.hasNext();
}
@Override
public S next() {
Map.Entry, S> en = it.next();
if (en.getValue() == null) {
en.setValue(en.getKey().provideService());
}
return en.getValue();
}
};
}
}
public static void jaclineRegisterService(Class service,
ServiceProvider implementation) {
JS_SERVICE_PROVIDERS.computeIfAbsent(service.toString(), k -> new LinkedHashMap<>()).put(
implementation, null);
}
@SuppressWarnings({"unchecked"})
public static ServiceLoader load(Class service) {
return new ServiceLoader(service, (Map, S>)(Map,?>) JS_SERVICE_PROVIDERS.get(
service.toString()));
}
public Optional findFirst() {
if (implementations == null || implementations.isEmpty()) {
return Optional.empty();
} else {
return Optional.of(iterator().next());
}
}
/**
* Returns a string describing this service.
*
* @return A descriptive string
*/
@Override
public String toString() {
return "java.util.ServiceLoader[" + service.getName() + "]";
}
}