ServiceLoader doesn't load implementation
Asked Answered
M

1

7

I really did a lot of research before asking this, it seems like I'm missing something. I try to implement a ServiceLoader and therefore made an example class:

Project structure

the code is simple:

testInterface.java

package com.test;

public interface testInterface {
    void test();
}

testImpl.java

package com.test;

public class testImpl implements testInterface {

    @Override
    public void test() {
        System.out.println("test");
    }

} 

Main.java

package com.test;

import java.util.ServiceLoader;

public class Main {

    public static void main(String[] args) {
        ServiceLoader<testInterface> serviceLoader = ServiceLoader.load(testInterface.class);

        serviceLoader.iterator().next().test();
    }

}

com.test.testInterface

com.test.testImpl

I keep getting a NoSuchElementException at the iterator part which means that the implementation was not loaded. Thanks in advance.

Mariano answered 29/10, 2015 at 22:8 Comment(0)
O
10

Put your META-INF/services/ into resources/ and add it to the Eclipse project as a source folder. It will be automatically included in the JAR file when you compile.

Organogenesis answered 29/10, 2015 at 22:51 Comment(3)
Thanks for the answer, I knew it would be something this simple. I saw this project structure in other videos / posts and thought it was correct, seems like it was wrong. Thank you so much!Mariano
I just had this problem; if anyone else is having it too, make sure that when the resources/ directory is linked, it's including that type of file. Took me forever to figure out; thanks Eclipse!Reel
If you're using modules, make sure to also add provides and uses statements in your module-info.java otherwise you run into the same NoSuchElementException! If the above example was contained in a module, you'll need to add: provides com.test.testInterface with com.test.testImpl; uses com.test.testInterface;Athalia

© 2022 - 2024 — McMap. All rights reserved.