0

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

  • `META-INF` must reside at the classpath root, hence it must be a sibling of `ServiceLoader_`. – Izruo Aug 31 '21 at 12:57
  • 1
    The general way to use an `Iterator`, is to call `hasNext()` *before* `next()`. And on the same iterator, instead of calling `iterator()` twice. – Holger Dec 20 '21 at 13:16

1 Answers1

0

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.

Izruo
  • 2,246
  • 1
  • 11
  • 23
  • Problem was that I didn't set the META-INF as Resources, after doing that It's working perfectly. Thanks for the suggestions. – M Nasir Baloch Sep 01 '21 at 07:05