Java Module-Info 'Uses' Directive (Service Consumption)

Viewed 170

I'm using one of the new random generator algorithms (https://openjdk.java.net/jeps/356):

RandomGeneratorFactory.of("L128X1024MixRandom").create().nextDouble();

And it works. Except after using jpackage tool (https://openjdk.java.net/jeps/392)

I get exception

No implementation of the random generator algorithm "L128X1024MixRandom" is available

I tried adding the uses directive to specify consuming the service in my module-info.java (https://docs.oracle.com/javase/specs/jls/se17/html/jls-7.html#jls-7.7.3)

uses java.util.random.RandomGenerator;

But that doesn't fix it or seem to matter being there (am I using it wrong? I would think this should be the solution).

Instead, I have to add jpackage option: --add-modules jdk.random

Repro Steps

1. Create directories with files:

rngTest/com/example/Test.java

package com.example;

import javax.swing.JOptionPane;
import java.util.random.RandomGeneratorFactory;

public class Test {
    public static void main(String[] args) throws Exception {
        try {
            JOptionPane.showMessageDialog(null, "nextDouble: " + RandomGeneratorFactory.of("L128X1024MixRandom").create().nextDouble());
        } catch (Exception e) {
            JOptionPane.showMessageDialog(null, "Exception: " + e.getMessage());
        }
    }
}

rngTest/module-info.java

module com.example {
    requires java.desktop;
    uses java.util.random.RandomGenerator;
}

rngTest/manifest.txt

Manifest-Version: 1.0
Created-By: 17.0.1
Build-Jdk-Spec: 17
Main-Class: com.example.Test

2. Run commands from the rngTest directory

(for macOS. Will need to change --type dmg for other platforms, see https://openjdk.java.net/jeps/392)

find . -name "*.java" > sources.txt
javac @sources.txt -d target
mkdir -p lib; cd target; jar cfm ../lib/test.jar ../manifest.txt *; cd ..
${JAVA_HOME}/bin/jpackage --module-path lib --module com.example/com.example.Test --type dmg --name Test

3. Run the created installer, then run the installed application

Notice exception message.

Now rerun jpackage command with --add-modules jdk.random and then repeat step 3, notice success.

${JAVA_HOME}/bin/jpackage --module-path lib --module com.example/com.example.Test --type dmg --name Test --add-modules jdk.random
1 Answers

I had tried adding requires jdk.random; to my module-info.java

It failed to compile with error "module not found: jdk.random"

(I figured its access was limited with only exporting to java.base)

But that was with maven-compiler-plugin:3.8.1

Turns out it does compile with javac and that works.

So maybe a bug with maven-compiler-plugin.

But I still think the uses directive should have worked. And I need to use the maven-compiler-plugin.

Related