com.sap.cds.Cds4jServiceLoader Maven / Gradle / Ivy
/************************************************************************
* © 2019-2024 SAP SE or an SAP affiliate company. All rights reserved. *
************************************************************************/
package com.sap.cds;
import java.util.Collection;
import java.util.Iterator;
import java.util.Map;
import java.util.Optional;
import java.util.ServiceLoader;
import java.util.concurrent.ConcurrentHashMap;
import com.google.common.collect.ImmutableList;
/**
* Internal ServiceLoader class.
*/
public final class Cds4jServiceLoader {
private static final Map> implementations = new ConcurrentHashMap<>();
private Cds4jServiceLoader() {
}
@SuppressWarnings("unchecked")
public static T load(Class clazz) {
Class> impl = implementations.computeIfAbsent(clazz.getCanonicalName(), c -> findImpl(clazz));
try {
return (T) impl.getDeclaredConstructor().newInstance();
} catch (Exception e) {
throw new CdsException("Failed to instantiate " + impl.getCanonicalName(), e);
}
}
@SuppressWarnings("unchecked")
private static Class findImpl(Class clazz) {
Iterator implClasses = ServiceLoader.load(clazz).iterator();
if (implClasses.hasNext()) {
return (Class) implClasses.next().getClass();
} else {
// Try same classloader as the requested Class
implClasses = ServiceLoader.load(clazz, clazz.getClassLoader()).iterator();
if (implClasses.hasNext()) {
return (Class) implClasses.next().getClass();
}
throw new CdsException("Cannot find implementation of " + clazz.getCanonicalName());
}
}
public static Optional find(Class clazz) {
try {
return Optional.of(load(clazz));
} catch (Exception e) {
return Optional.empty();
}
}
public static Collection loadAll(Class clazz) {
Iterator implClasses = ServiceLoader.load(clazz).iterator();
if (!implClasses.hasNext()) {
implClasses = ServiceLoader.load(clazz, clazz.getClassLoader()).iterator();
}
return ImmutableList.copyOf(implClasses);
}
}
© 2015 - 2025 Weber Informatics LLC | Privacy Policy