Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ServiceLoader doesn't load implementation

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.

like image 228
Hr. Burtz Avatar asked Oct 29 '15 22:10

Hr. Burtz


1 Answers

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.

like image 93
user5500105 Avatar answered Oct 15 '22 02:10

user5500105