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

com.hyf.hotrefresh.common.Services Maven / Gradle / Ivy

package com.hyf.hotrefresh.common;

import java.util.*;

/**
 * @author baB_hyf
 * @date 2022/05/20
 */
public class Services {

    private static final List extendServices = new ArrayList<>();

    static {
        ServiceLoader services = ServiceLoader.load(ExtensionService.class);
        services.forEach(extendServices::add);
    }

    public static  List gets(Class clazz) {
        return gets(clazz, Thread.currentThread().getContextClassLoader());
    }

    public static  List gets(Class clazz, ClassLoader classLoader) {

        List svcs = new ArrayList<>();

        ServiceLoader services = ServiceLoader.load(clazz, classLoader);
        services.forEach(svcs::add);

        for (ExtensionService extendService : extendServices) {
            try {
                List extendServices = extendService.getExtensionServices(clazz);
                svcs.addAll(extendServices);
            } catch (Throwable t) {
                Log.error("Get extend services failed", t);
            }
        }

        filterSameClass(svcs);
        return svcs;
    }

    @SuppressWarnings("unchecked")
    private static  void filterSameClass(List svcs) {
        Set> classSet = new HashSet<>();
        svcs.removeIf(svc -> !classSet.add((Class) svc.getClass()));
    }
}