java 动态加载,Java动态加载插件

I want to make an application that can dynamically load plug-ins but I've not found any literature on Internet.

The difficult thing is: I don't know the name in advance.

For example I've a Plugin interface:

public interface Plugin {

public static Plugin newPlugin();

public void executePlugin(String args[]);

}

So that every Class implementing Plugin in the jar file are instantiated in a list:

Method method = classToLoad.getMethod ("newPlugin");

mylist.add(method.invoke(null);

First problem is, I cannot have a static method in an interface.

Second problem is, I don't know how to find all classes that implement an interface

Thanks for your help.

解决方案

So it seems like you want to dynamically discover Classes that implement a specific interface (e.g., Plugin) at runtime. You have basically two choices for this:

Use a component framework like osgi

Use Java's internal discovery process (ServiceLoader)

Since there are many good tutorials on osgi (also small ones), I will not detail that here. To use Java's internal discovery process, you need to do the following:

Bundle all "new" classes that you wish to discover into a jar file

Create a new file inside the jar file: META-INF/services/package.Plugin You must use the full package qualifier here

This file is a simple text file and contains the fully qualified name of each class implementing Plugin in that jar-file

Place that jar file into the classpath of your (potentially already running) application

Discover the services:

Service discovery is done like this:

ServiceLoader loader = ServiceLoader.load(Plugin.class)

for (Plugin p : loader) {

// do something with the plugin

}

As for static methods in interfaces: not possible. The semantics of that would also be somewhat weird as static methods are accessible without an instance of a class, and interfaces just define the methods, without any functionality. Thus, static would allow to call Interface.doSomething() whereas the interface does not define any functionality, this leads just to confusion.

edit:

added description what should be in the meta-file

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值