1
0

More than 1 year has passed since last update.

徹底攻略Java SE 11 Gold問題集[1Z0-816]対応の総仕上げ問題62(module)について

Last updated at Posted at 2023-03-06

gold問題集の問題62の回答に、選択肢B)module clientでrequires provider;する必要がある
というのが回答になっている、が、切らなくても正常に動く。

requiresはあくまでもmoduleとしての依存であって、class依存ではない認識

usesは公開というよりも使用する、消費するという意味。

ちなみに1モジュールのmodule-info.javaではprovideを1個しかかけないようだが
providerモジュールを追加すれば、そちらでもprovideできる。
その場合、ServiceLoader.load(SampleInterface.class)は、provideされた2個の
implが登録されている。for(xx:ServiceLoader x)で回してやると2個分のimpleが
動かせる。

自分はこんな環境で実行できた。

Api\module-info.java
module Api {
    exports api;
}
Provider\module-info.java
module Provider {
    requires Api;
    provides api.SampleInterface with provider.SampleImplClass;
}
Client\module-info.java
module Client {
    requires Api;
    uses api.SampleInterface;
}
api.Api.java
public interface SampleInterface{
    void method();
}
provider.SampleImplClass.java
public class SampleImplClass implements SampleInterface{

    @Override
    public void method() {
        System.out.println("sampleimplclass method");
    }
}
client.Client.java
public class Client {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        ServiceLoader<SampleInterface> sl = ServiceLoader.load(SampleInterface.class);
        for(SampleInterface si:sl){
            si.method();
        }
    }
    
}
1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0