javamavenannotation-processingmaven-compiler-pluginmodule-info

ServiceLoader not finding any services


I'm facing an issue where ServiceLoader does not find one provided service.

I have tested with regular project and the following sources:

// test/Tester.java
package test;

public interface Tester {
}

// test/TesterImpl.java
package test;

public class TesterImpl implements Tester {
}

// test/Runner.java
package test;

import java.util.ServiceLoader;

public class Runner {
    public static void main(String[] args) {
        var loader = ServiceLoader.load(Tester.class);
        for (var tester : loader) {
            System.out.println(tester);
        }
    }
}

// module-info.java
import test.Tester;
import test.TesterImpl;

module module {
    uses Tester;
    provides Tester with TesterImpl;
}

The above prints something akin to test.TesterImpl@1fb3ebeb, proving that it works as wanted.

The same fails to work when I try to use ServiceLoader.load(...) inside an AbstractProcessor that's run through maven-compiler-plugin. The processor returns an empty iterator instead. What is required to make it behave the same way in the annotation processor as it does in the case above?


Solution

  • THe solution to this issue was to specify a class loader - it appears that the annotation processor used a different classloader than the classes I was trying to load the services from. Solution is the following:

    ServiceLoader.load(MyService.class, MyAnnotationProcessor.class.getClassLoader())