javaserviceloaderserviceloader

Service Loader Class In Java, Having Issue with META-INF/services folder


I'm stuck in service loader class(java) can anybody help, here is my code and pic attached with it. see the pic to understand completely and tell me what's the issue

Interface Code

package ServiceLoader_.SL;

interface Account {
    String getMessage();
}

Class implementing that interface

package ServiceLoader_.SL;

public class Message implements Account {

    @Override
    public String getMessage() { 
        return "Hello";
    }
}

Main class

package ServiceLoader_.SL;

import java.util.ServiceLoader;

public class main {
    public static void main(String[] args) {
        ServiceLoader<Account> ac = ServiceLoader.load(Account.class);
        Account ab = ac.iterator().next();
        if(ac.iterator().hasNext()){
            System.out.println("hay^");
        }
    }
}

Gives error that no such element found when trying to access ac.iterator().next()

Click HereTo See Image


Solution

  • As specified by the documentation of ServiceLoader, the provider-configuration file must be part of the classpath and for ServiceLoader<Account> will be resolved as

    META-INF/services/ServiceLoader_.SL.Account
    

    Based on what I can deduct from the image, your file seems to reside at

    ServiceLoader_/META-INF/services/ServiceLoader_.SL.Account
    

    which the ServiceLoader implementation is unaware of, thus it will not locate (and therefore not provide) the implementation class ServiceLoader_.SL.Message.

    To fix this issue you must move the META-INF to the classpath root. Since I do not recognize the IDE shown in the image, I cannot say how one can do that though.