本文整理匯總了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;
}
示例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;
}
}
示例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;
}
}
}
示例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;
}
示例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);
}
示例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);
}
示例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)));
}
示例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();
}
示例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;
}
示例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);
}
示例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"));
}
示例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;
}
}
示例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);
}
}
示例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);
}
示例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;
}
}
}