- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
When to use the ServiceLoader class in a module in Java 9?
Java has a ServiceLoader class from java.util package that can help to locate service providers at the runtime by searching in the classpath. For service providers defined in modules, we can look at the sample application to declare modules with service and how it works.
For instance, we have a "test.app" module that we need to use Logger that can be retrieved from System.getLogger() factory method with the help of LoggerFinder service.
module com.tutorialspoint.test.app { requires java.logging; exports com.tutorialspoint.platformlogging.app; uses java.lang.System.LoggerFinder; }
Below is the test.app.MainApp class:
package com.tutorialspoint.platformlogging.app; public class MainApp { private static Logger LOGGER = System.getLogger(); public static void main(String args[]) { LOGGER.log(); } }
This is LoggerFinder implementation inside the "test.logging" module:
package com.tutorialspoint.platformlogging.logger; public class MyLoggerFinder extends LoggerFinder { @Override public Logger getLogger(String name, Module module) { // return a Logger depending on name/module } }
In "test.logging" module declaration, we can provide an implementation of LoggerFinder service with a "provides – with" clause.
module com.tutorialspoint.test.logging { provides java.lang.System.LoggerFinder with com.tutorialspoint.platformlogging.logger.MyLoggerFinder; }
Advertisements