當前位置: 首頁>>代碼示例>>Java>>正文


Java ServiceLoader類代碼示例

本文整理匯總了Java中java.util.ServiceLoader的典型用法代碼示例。如果您正苦於以下問題:Java ServiceLoader類的具體用法?Java ServiceLoader怎麽用?Java ServiceLoader使用的例子?那麽, 這裏精選的類代碼示例或許可以為您提供幫助。


ServiceLoader類屬於java.util包,在下文中一共展示了ServiceLoader類的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Java代碼示例。

示例1: createObjectMapper

import java.util.ServiceLoader; //導入依賴的package包/類
public static ObjectMapper createObjectMapper() {
    final YAMLFactory yamlFactory = new YAMLFactory()
        .configure(YAMLGenerator.Feature.USE_NATIVE_TYPE_ID, false)
        .configure(YAMLGenerator.Feature.MINIMIZE_QUOTES, true)
        .configure(YAMLGenerator.Feature.ALWAYS_QUOTE_NUMBERS_AS_STRINGS, true)
        .configure(YAMLGenerator.Feature.USE_NATIVE_TYPE_ID, false);

    ObjectMapper mapper = new ObjectMapper(yamlFactory)
        .registerModule(new Jdk8Module())
        .setSerializationInclusion(JsonInclude.Include.NON_EMPTY)
        .enable(SerializationFeature.INDENT_OUTPUT)
        .disable(SerializationFeature.WRITE_NULL_MAP_VALUES);

    for (Step step : ServiceLoader.load(Step.class, YamlHelpers.class.getClassLoader())) {
        mapper.registerSubtypes(new NamedType(step.getClass(), step.getKind()));
    }

    return mapper;
}
 
開發者ID:syndesisio,項目名稱:syndesis,代碼行數:20,代碼來源:YamlHelpers.java

示例2: findServiceProvider

import java.util.ServiceLoader; //導入依賴的package包/類
private static <T> T findServiceProvider(final Class<T> type)
        throws DatatypeConfigurationException
{
    try {
        return AccessController.doPrivileged(new PrivilegedAction<T>() {
            public T run() {
                final ServiceLoader<T> serviceLoader = ServiceLoader.load(type);
                final Iterator<T> iterator = serviceLoader.iterator();
                if (iterator.hasNext()) {
                    return iterator.next();
                } else {
                    return null;
                }
            }
        });
    } catch(ServiceConfigurationError e) {
        final DatatypeConfigurationException error =
                new DatatypeConfigurationException(
                    "Provider for " + type + " cannot be found", e);
        throw error;
    }
}
 
開發者ID:AdoptOpenJDK,項目名稱:openjdk-jdk10,代碼行數:23,代碼來源:FactoryFinder.java

示例3: loadProviderAsService

import java.util.ServiceLoader; //導入依賴的package包/類
private static AsynchronousChannelProvider loadProviderAsService() {
    ServiceLoader<AsynchronousChannelProvider> sl =
        ServiceLoader.load(AsynchronousChannelProvider.class,
                           ClassLoader.getSystemClassLoader());
    Iterator<AsynchronousChannelProvider> i = sl.iterator();
    for (;;) {
        try {
            return (i.hasNext()) ? i.next() : null;
        } catch (ServiceConfigurationError sce) {
            if (sce.getCause() instanceof SecurityException) {
                // Ignore the security exception, try the next provider
                continue;
            }
            throw sce;
        }
    }
}
 
開發者ID:SunburstApps,項目名稱:OpenJSharp,代碼行數:18,代碼來源:AsynchronousChannelProvider.java

示例4: loadBuilders

import java.util.ServiceLoader; //導入依賴的package包/類
private static Map<String, HandlerBuilder> loadBuilders(final ClassLoader classLoader) {
    ServiceLoader<HandlerBuilder> loader = ServiceLoader.load(HandlerBuilder.class, classLoader);
    final Map<String, HandlerBuilder> ret = new HashMap<>();
    for (HandlerBuilder builder : loader) {
        if (ret.containsKey(builder.name())) {
            if (ret.get(builder.name()).getClass() != builder.getClass()) {
                throw UndertowMessages.MESSAGES.moreThanOneHandlerWithName(builder.name(), builder.getClass(), ret.get(builder.name()).getClass());
            }
        } else {
            ret.put(builder.name(), builder);
        }
    }
    return ret;
}
 
開發者ID:lamsfoundation,項目名稱:lams,代碼行數:15,代碼來源:HandlerParser.java

示例5: init

import java.util.ServiceLoader; //導入依賴的package包/類
/**
 * Load {@link BeanPropertyPostProcessor}s from <code>META-INF/services</code> extensions.
 * @param classLoader ClassLoader to use
 * @return {@link BeanPropertyPostProcessor}s list, empty if none found
 */
private void init(final ClassLoader classLoader) {
	LOGGER.debug(() -> "Load BeanPropertyPostProcessors for classloader [" + classLoader
			+ "] using ServiceLoader with service name: " + BeanPropertyPostProcessor.class.getName());
	Iterable<BeanPropertyPostProcessor> postProcessors = AccessController
			.doPrivileged(new PrivilegedAction<Iterable<BeanPropertyPostProcessor>>() {
				@Override
				public Iterable<BeanPropertyPostProcessor> run() {
					return ServiceLoader.load(BeanPropertyPostProcessor.class, classLoader);
				}
			});
	postProcessors.forEach(pr -> {
		propertyPostProcessors.add(pr);
		LOGGER.debug(() -> "Loaded and registered BeanPropertyPostProcessor [" + pr + "] for classloader ["
				+ classLoader + "]");
	});
	// sort by priority
	Collections.sort(propertyPostProcessors, PRIORITY_COMPARATOR);
}
 
開發者ID:holon-platform,項目名稱:holon-core,代碼行數:24,代碼來源:DefaultBeanIntrospector.java

示例6: validateServiceIsLocatableViaServiceLoader

import java.util.ServiceLoader; //導入依賴的package包/類
@Test
public void validateServiceIsLocatableViaServiceLoader() {
    ServiceLoader<Processor> loader = ServiceLoader.<Processor> load(Processor.class);
    Iterator<Processor> iter = loader.iterator();
    boolean pubJmsPresent = false;
    boolean consumeJmsPresent = false;
    while (iter.hasNext()) {
        Processor p = iter.next();
        if (p.getClass().getSimpleName().equals(PublishJMS.class.getSimpleName())) {
            pubJmsPresent = true;
        } else if (p.getClass().getSimpleName().equals(ConsumeJMS.class.getSimpleName())) {
            consumeJmsPresent = true;
        }

    }
    assertTrue(pubJmsPresent);
    assertTrue(consumeJmsPresent);
}
 
開發者ID:lsac,項目名稱:nifi-jms-jndi,代碼行數:19,代碼來源:CommonTest.java

示例7: main

import java.util.ServiceLoader; //導入依賴的package包/類
public static void main(String[] args) {
    ServiceLoader<Analysis> analyses = ServiceLoader.load(Analysis.class);
  //  analyses.stream().map(ServiceLoader.Provider::get).forEach(analyzer -> System.out.println(analyzer.getName()));
    Set<Analysis> collect = analyses.stream()
                                    .filter(p -> isAnno(p.type()))
                                    .map(ServiceLoader.Provider::get).collect(Collectors.toSet());

    Person nao = new Person(0, 0);
    Person miniperson = new Person(10, 0);
    Person minperson = new Person(1001, 0);
    Person minxperson = new Person(1001, 11);
    Person maxperson = new Person(100000, 11);
    Person maxxperson = new Person(100000, 26);
    Person poorperson = new Person(100000, 0);

    collect.forEach(p->System.out.println(p.analyze(maxxperson)));


}
 
開發者ID:kkTranslation,項目名稱:Java-9-Spring-Webflux,代碼行數:20,代碼來源:Gui.java

示例8: DefaultSqlConfig

import java.util.ServiceLoader; //導入依賴的package包/類
/**
 * コンストラクタ
 *
 * @param connectionSupplier コネクションサプライヤ
 * @param loadPath SQLファイルの読み込みルートパス
 */
private DefaultSqlConfig(final ConnectionSupplier connectionSupplier, final String loadPath) {
	super();
	this.connectionSupplier = connectionSupplier;

	this.sqlManager = new SqlManagerImpl(loadPath);
	this.sqlFilterManager = new SqlFilterManagerImpl();
	this.sqlContextFactory = new SqlContextFactoryImpl();
	this.entityHandler = new DefaultEntityHandler();

	this.dialect = StreamSupport.stream(ServiceLoader.load(Dialect.class).spliterator(), false).filter(d -> d.accept(connectionSupplier)).findFirst().orElseGet(DefaultDialect::new);

	this.sqlAgentFactory = new SqlAgentFactoryImpl(this);

	initialize();
}
 
開發者ID:future-architect,項目名稱:uroborosql,代碼行數:22,代碼來源:DefaultSqlConfig.java

示例9: findServices

import java.util.ServiceLoader; //導入依賴的package包/類
/**
 * Looks for all "META-INF/services/[className]" files and
 * create one instance for each class name found inside this file.
 */
private <T> List<T> findServices(Class<T> clazz) {
    final List<T> result = new ArrayList<>();
    final boolean debug = getDebugPropertyValue();
    try {
        // TCCL allows user plugins to be loaded even if xjc is in jdk
        // We have to use our SecureLoader to obtain it because we are trying to avoid SecurityException
        final ClassLoader tccl = SecureLoader.getContextClassLoader();
        final ServiceLoader<T> sl = ServiceLoader.load(clazz, tccl);
        for (T t : sl)
            result.add(t);
    } catch (Throwable e) {
        // ignore any error
        StringWriter w = new StringWriter();
        e.printStackTrace(new PrintWriter(w));
        pluginLoadFailure = w.toString();
        if (debug)
            System.out.println(pluginLoadFailure);
    }
    return result;
}
 
開發者ID:AdoptOpenJDK,項目名稱:openjdk-jdk10,代碼行數:25,代碼來源:Options.java

示例10: loadTokenParser

import java.util.ServiceLoader; //導入依賴的package包/類
@BeforeClass(alwaysRun=true)
public static void loadTokenParser() throws Exception {
    System.out.printf("TokenValidationTest.initClass\n");
    publicKey = TokenUtils.readPublicKey("/publicKey.pem");
    if(publicKey == null) {
        throw new IllegalStateException("Failed to load /publicKey.pem resource");
    }

    // Load the ITokenParser via the ServiceLoader
    ServiceLoader<ITokenParser> serviceLoader = ServiceLoader.load(ITokenParser.class);
    if(serviceLoader.iterator().hasNext() == false) {
        // Try to obtain ITokenParser via CDI
        tokenParser = CDI.current().select(ITokenParser.class).get();
        if(tokenParser == null) {
            throw new IllegalStateException(String.format("An %s service provider or producer is required", ITokenParser.class.getName()));
        }
    }
    else {
        tokenParser = serviceLoader.iterator().next();
        if (tokenParser == null) {
            throw new IllegalStateException(String.format("Service provider for %s  produced a null parser", ITokenParser.class.getName()));
        }
    }
    System.out.printf("Using ITokenParser: %s\n", tokenParser);
}
 
開發者ID:eclipse,項目名稱:microprofile-jwt-auth,代碼行數:26,代碼來源:TokenValidationTest.java

示例11: testWithCustomLayer1

import java.util.ServiceLoader; //導入依賴的package包/類
/**
 * Basic test of ServiceLoader.load, using the class loader for
 * a module in a custom layer as the context.
 */
@Test
public void testWithCustomLayer1() {
    ModuleLayer layer = createCustomLayer("bananascript");

    ClassLoader loader = layer.findLoader("bananascript");
    List<ScriptEngineFactory> providers
        = collectAll(ServiceLoader.load(ScriptEngineFactory.class, loader));

    // should have at least 2 x bananascript + pearscript
    assertTrue(providers.size() >= 3);

    // first element should be the provider in the custom layer
    ScriptEngineFactory factory = providers.get(0);
    assertTrue(factory.getClass().getClassLoader() == loader);
    assertTrue(factory.getClass().getModule().getLayer() == layer);
    assertTrue(factory.getEngineName().equals("BananaScriptEngine"));

    // remainder should be the boot layer
    providers.remove(0);
    Set<String> names = providers.stream()
            .map(ScriptEngineFactory::getEngineName)
            .collect(Collectors.toSet());
    assertTrue(names.contains("BananaScriptEngine"));
    assertTrue(names.contains("PearScriptEngine"));
}
 
開發者ID:AdoptOpenJDK,項目名稱:openjdk-jdk10,代碼行數:30,代碼來源:ModulesTest.java

示例12: run

import java.util.ServiceLoader; //導入依賴的package包/類
@Override
public LoggingBackend run() {
    final Iterator<LoggerFinder> iterator =
        ServiceLoader.load(LoggerFinder.class, ClassLoader.getSystemClassLoader())
        .iterator();
    if (iterator.hasNext()) {
        return LoggingBackend.CUSTOM; // Custom Logger Provider is registered
    }
    // No custom logger provider: we will be using the default
    // backend.
    final Iterator<DefaultLoggerFinder> iterator2 =
        ServiceLoader.loadInstalled(DefaultLoggerFinder.class)
        .iterator();
    if (iterator2.hasNext()) {
        // LoggingProviderImpl is registered. The default
        // implementation is java.util.logging
        String cname = System.getProperty("java.util.logging.config.class");
        String fname = System.getProperty("java.util.logging.config.file");
        return (cname != null || fname != null)
            ? LoggingBackend.JUL_WITH_CONFIG
            : LoggingBackend.JUL_DEFAULT;
    } else {
        // SimpleConsoleLogger is used
        return LoggingBackend.NONE;
    }
}
 
開發者ID:AdoptOpenJDK,項目名稱:openjdk-jdk10,代碼行數:27,代碼來源:BootstrapLogger.java

示例13: getPlugins

import java.util.ServiceLoader; //導入依賴的package包/類
/**
 * The plugins accessible in the current context.
 *
 * @param pluginsLayer
 * @return The list of plugins.
 */
private static <T extends Plugin> List<T> getPlugins(Class<T> clazz, ModuleLayer pluginsLayer) {
    Objects.requireNonNull(pluginsLayer);
    List<T> factories = new ArrayList<>();
    try {
        Iterator<T> providers
                = ServiceLoader.load(pluginsLayer, clazz).iterator();
        while (providers.hasNext()) {
            factories.add(providers.next());
        }
        registeredPlugins.values().stream().forEach((fact) -> {
            if (clazz.isInstance(fact)) {
                @SuppressWarnings("unchecked")
                T trans = (T) fact;
                factories.add(trans);
            }
        });
        return factories;
    } catch (Exception ex) {
        throw new PluginException(ex);
    }
}
 
開發者ID:AdoptOpenJDK,項目名稱:openjdk-jdk10,代碼行數:28,代碼來源:PluginRepository.java

示例14: registerInstalledProviders

import java.util.ServiceLoader; //導入依賴的package包/類
private void registerInstalledProviders() {
    /*
      We need to load installed providers from the
      system classpath (typically the <code>lib/ext</code>
      directory in in the Java installation directory)
      in the privileged mode in order to
      be able read corresponding jar files even if
      file read capability is restricted (like the
      applet context case).
     */
    PrivilegedAction doRegistration =
        new PrivilegedAction() {
            public Object run() {
                Iterator categories = getCategories();
                while (categories.hasNext()) {
                    Class<IIOServiceProvider> c = (Class)categories.next();
                    for (IIOServiceProvider p : ServiceLoader.loadInstalled(c)) {
                        registerServiceProvider(p);
                    }
                }
                return this;
            }
        };

    AccessController.doPrivileged(doRegistration);
}
 
開發者ID:lambdalab-mirror,項目名稱:jdk8u-jdk,代碼行數:27,代碼來源:IIORegistry.java

示例15: testStreamOrder

import java.util.ServiceLoader; //導入依賴的package包/類
/**
 * Basic test of stream() to ensure that elements for providers in named
 * modules come before elements for providers in unnamed modules.
 */
@Test
public void testStreamOrder() {
    List<Class<?>> types = ServiceLoader.load(ScriptEngineFactory.class)
            .stream()
            .map(Provider::type)
            .collect(Collectors.toList());

    boolean foundUnnamed = false;
    for (Class<?> factoryClass : types) {
        if (factoryClass.getModule().isNamed()) {
            if (foundUnnamed) {
                assertTrue(false, "Named module element after unnamed");
            }
        } else {
            foundUnnamed = true;
        }
    }
}
 
開發者ID:AdoptOpenJDK,項目名稱:openjdk-jdk10,代碼行數:23,代碼來源:ModulesTest.java


注:本文中的java.util.ServiceLoader類示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。