可扩展性

可扩展性

SpiLoader

public final class SpiLoader {

    public static <T> T loadFirstInstanceOrDefault(Class<T> clazz, Class<? extends T> defaultClass) {
        AssertUtil.notNull(clazz, "SPI class cannot be null");
        AssertUtil.notNull(defaultClass, "default SPI class cannot be null");
        try {
            String key = clazz.getName();
            // Not thread-safe, as it's expected to be resolved in a thread-safe context.
            ServiceLoader<T> serviceLoader = SERVICE_LOADER_MAP.get(key);
            if (serviceLoader == null) {
                serviceLoader = ServiceLoaderUtil.getServiceLoader(clazz);
                SERVICE_LOADER_MAP.put(key, serviceLoader);
            }

            for (T instance : serviceLoader) {
                if (instance.getClass() != defaultClass) {
                    return instance;
                }
            }
            return defaultClass.newInstance();
        } catch (Throwable t) {
            RecordLog.error("[SpiLoader] ERROR: loadFirstInstanceOrDefault failed", t);
            t.printStackTrace();
            return null;
        }
    }
    
}