Home > Java > javaTutorial > body text

In Java 9, when to use ServiceLoader class in a module?

PHPz
Release: 2023-08-25 19:05:02
forward
1504 people have browsed it

在Java 9中,何时使用ServiceLoader类在模块中呢?

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>
Copy after login

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();
   }
}
Copy after login

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
   }
}
Copy after login

in the "

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>
Copy after login

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!

source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template