Java has a ServiceLoader class from the java.util package that can help position Services provide providers at runtime by searching in the classpath. For service providers defined in modules, we can look at the sample application to declare a module with services and how it works.
For example, we have a "test.appneed to use the Logger module, we can use the 我们需要使用 Logger 模块,可以借助 LoggerFinder service from the System.getLogger() factory method Retrieve the Logger.
<strong>module com.tutorialspoint.test.app { requires java.logging; exports com.tutorialspoint.platformlogging.app; uses java.lang.System.LoggerFinder; }</strong>
The following is the test.app.MainApp class:
package com.tutorialspoint.platformlogging.app; public class MainApp { private static <strong>Logger </strong>LOGGER = <strong>System.getLogger()</strong>; public static void main(String args[]) { LOGGER.log(); } }
This is "##LoggerFinder within #test implements the ".logging" module:
package com.tutorialspoint.platformlogging.logger; public class MyLoggerFinder extends LoggerFinder { <strong>@Override</strong> public Logger getLogger(String name, Module module) { // return a Logger depending on name/module } }
test.logging" module declaration, We may provide an implementation of the LoggerFinder service via the " OFFER – " terms.
<strong>module com.tutorialspoint.test.logging { provides java.lang.System.LoggerFinder with com.tutorialspoint.platformlogging.logger.MyLoggerFinder; }</strong>
The above is the detailed content of In Java 9, when to use ServiceLoader class in a module?. For more information, please follow other related articles on the PHP Chinese website!