Issue #4340 - changes from review

Signed-off-by: Lachlan Roberts <lachlan@webtide.com>
This commit is contained in:
Lachlan Roberts 2020-03-17 15:14:52 +11:00
parent 30d36ed68c
commit 9363a3c39a
2 changed files with 21 additions and 14 deletions

View File

@ -36,16 +36,16 @@ class ServiceLoaderSpliterator<T> implements Spliterator<ServiceLoader.Provider<
@Override
public boolean tryAdvance(Consumer<? super ServiceLoader.Provider<T>> action)
{
Provider<T> next = new Provider<>();
ServiceProvider<T> next;
try
{
if (!iterator.hasNext())
return false;
next.setServiceProvider(iterator.next());
next = new ServiceProvider<>(iterator.next());
}
catch (Throwable t)
{
next.setError(t);
next = new ServiceProvider<>(t);
}
action.accept(next);
@ -70,18 +70,25 @@ class ServiceLoaderSpliterator<T> implements Spliterator<ServiceLoader.Provider<
return Spliterator.ORDERED;
}
private static class Provider<T> implements ServiceLoader.Provider<T>
/**
* An implementation of the {@link ServiceLoader.Provider} which contains either an instance of the service or
* an error to be thrown when someone calls {@link #get()}.
* @param <T> the service type.
*/
private static class ServiceProvider<T> implements ServiceLoader.Provider<T>
{
private T serviceProvider;
private Throwable error;
private final T service;
private final Throwable error;
public void setServiceProvider(T serviceProvider)
public ServiceProvider(T service)
{
this.serviceProvider = serviceProvider;
this.service = service;
this.error = null;
}
public void setError(Throwable error)
public ServiceProvider(Throwable error)
{
this.service = null;
this.error = error;
}
@ -95,9 +102,9 @@ class ServiceLoaderSpliterator<T> implements Spliterator<ServiceLoader.Provider<
@Override
public T get()
{
if (error != null)
if (service == null)
throw new ServiceConfigurationError("", error);
return serviceProvider;
return service;
}
}
}

View File

@ -767,7 +767,7 @@ public class TypeUtil
* @param provider The service provider to instantiate.
* @return a stream of the loaded service providers.
*/
public static <T> Stream<T> providerMap(ServiceLoader.Provider<T> provider)
public static <T> Stream<T> mapToService(ServiceLoader.Provider<T> provider)
{
try
{
@ -782,14 +782,14 @@ public class TypeUtil
/**
* Shortcut method combining {@link #serviceProviderStream(ServiceLoader)} with
* with {@link #providerMap(ServiceLoader.Provider)} using {@link Stream#flatMap(Function)}.
* with {@link #mapToService(ServiceLoader.Provider)} using {@link Stream#flatMap(Function)}.
* @param serviceLoader the ServiceLoader instance to use.
* @param <T> the type of the service to load.
* @return a stream of the service provider type which will not throw {@link ServiceConfigurationError}.
*/
public static <T> Stream<T> serviceStream(ServiceLoader<T> serviceLoader)
{
return serviceProviderStream(serviceLoader).flatMap(TypeUtil::providerMap);
return serviceProviderStream(serviceLoader).flatMap(TypeUtil::mapToService);
}
/**