Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Java

uses — declaring service consumption in a module

The uses directive in module-info.java identifies a service type whose providers the module may discover through ServiceLoader. It neither selects a particular implementation nor starts discovery by itself. uses is a contextual keyword, not a reserved keyword.

Version: Java SE 21; repository runtime, production runtime not attested

Syntax

module ModuleName {
    uses ServiceType;
}

uses ServiceType; belongs inside the module declaration in module-info.java. The service type is a contract, usually an interface, and a provider supplies an implementation. uses is a contextual keyword: it has special meaning in this position, but outside the relevant context it can be an identifier, such as a variable name.

The directive declares service consumption; code performs discovery through java.util.ServiceLoader. It does not automatically create instances or guarantee that a provider will be found. When code in an explicit module calls ServiceLoader.load(ServiceType.class), the service-use check is satisfied if the module declares the corresponding uses directive or has added the service use at run time with Module.addUses. If neither is in place, the call throws ServiceConfigurationError.

Do not confuse uses with requires or provides ... with ...: requires declares a module dependency, while provides registers a provider. If the service belongs to another module, its type must be accessible to the consumer; uses does not replace the necessary dependency or package export. A dependency on the particular provider module is not required.

The service type cannot be an enum class. Repeating uses for the same service in one module declaration is a compile-time error. The example places the consumer and its only provider in one module to remain self-contained. The nested Hello class is public and static and has a public no-argument constructor.

Examples

// src/demo/module-info.java
module demo {
    uses demo.Main.Greeting;
    provides demo.Main.Greeting with demo.Main.Hello;
}

// src/demo/demo/Main.java
package demo;

import java.util.ServiceLoader;

public class Main {
    public interface Greeting {
        String message();
    }

    public static class Hello implements Greeting {
        public Hello() {}

        @Override
        public String message() {
            return "Hello";
        }
    }

    public static void main(String[] args) {
        Greeting greeting = ServiceLoader.load(Greeting.class)
                .findFirst().orElseThrow();
        System.out.println(greeting.message());
    }
}

Result

Hello

The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.

Sources