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

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

PHPz
PHPzforward
2023-08-25 19:05:021444browse

在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>

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
   }
}

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>

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!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete