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.

Dezza
  • 1,094
  • 4
  • 22
  • 25
Hr. Burtz
  • 73
  • 1
  • 7

1 Answers1

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.

user5500105
  • 297
  • 2
  • 7
  • 2
    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! – Hr. Burtz Oct 29 '15 at 23:08
  • 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! – Willwsharp Jul 28 '17 at 19:39
  • 1
    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;` – UrbenLegend Aug 25 '20 at 03:22