Best approach to dynamically load modules (classes) in Java

前端 未结 3 2212
南方客
南方客 2021-02-09 12:10

I\'m currently writing an application that requires to operate on different type of devices. My approach would be to make a \"modular\" application that can dynamically load dif

3条回答
  •  天命终不由人
    2021-02-09 12:35

    Additionnaly to the ServicerLoader usage given by @SeverityOne, you can use the module-info.java to declare the different instanciation of the interface, using "uses"/"provides" keywords.

    Then you use a module path instead of a classpath, it loads all the directory containing your modules, don't need to create a specific classLoader

    The serviceLoader usage:

    public static void main(String[] args) {
        ServiceLoader sl = ServiceLoader.load(IGreeting.class);
        IGreeting greeting = sl.findFirst().orElseThrow(NullPointerException::new);
        System.out.println( greeting.regular("world"));
    }
    

    In the users project:

    module pl.tfij.java9modules.app {
        exports pl.tfij.java9modules.app;
        uses pl.tfij.java9modules.app.IGreeting;
    }
    

    In the provider project:

    module pl.tfij.java9modules.greetings {
        requires pl.tfij.java9modules.app;
        provides pl.tfij.java9modules.app.IGreeting
                with pl.tfij.java9modules.greetings.Greeting;
    }
    

    And finally the CLI usage

    java --module-path mods --module pl.tfij.java9modules.app
    

    Here is an example; Github example (Thanks for "tfij/" repository initial exemple)

    Edit, I realized the repository already provides decoupling examples: https://github.com/tfij/Java-9-modules---reducing-coupling-of-modules

提交回复
热议问题