Dynamically loading plugin jars using ServiceLoader

坚强是说给别人听的谎言 提交于 2019-11-27 10:44:50
MaxArt

The problem was very simple. And stupid. In the plugin .jar files the /services/plugintest.SimplePlugin file was missing inside the META-INF directory, so the ServiceLoader couldn't identify the jars as services and load the class.

That's pretty much all, the second (and cleaner) way works like a charm.

Starting from Java 9 the service providing scanning will be much easier and efficient. No more need for META-INF/services.

In the interface module declaration declare:

uses com.foo.spi.Service;

And in the provider's module:

provides com.foo.spi.Service with com.bar.ServiceImplementation

The solution for your application concept has been already described in Oracle Documentation (including dynamically loading JARs)

Creating Extensible Applications With the Java Platform http://www.oracle.com/technetwork/articles/javase/extensible-137159.html

on the bottom of the article you will find links to

  • source code of the example
  • Javadoc ServiceLoader API

In my opinion it is better to slightly modify Oracle's example than reinventing the wheel as Omer Schleifer said.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!