java 运行时 添加jar文件_如何在运行时加载jar文件[重复]

使用org.openide.util.Lookup和ClassLoader动态加载Jar插件,如下所示 .

public LoadEngine() {

Lookup ocrengineLookup;

Collection ocrengines;

Template ocrengineTemplate;

Result ocrengineResults;

try {

//ocrengineLookup = Lookup.getDefault(); this only load OCREngine in classpath of application

ocrengineLookup = Lookups.metaInfServices(getClassLoaderForExtraModule());//this load the OCREngine in the extra module as well

ocrengineTemplate = new Template(OCREngine.class);

ocrengineResults = ocrengineLookup.lookup(ocrengineTemplate);

ocrengines = ocrengineResults.allInstances();//all OCREngines must implement the defined interface in OCREngine. Reference to guideline of implement org.openide.util.Lookup for more information

} catch (Exception ex) {

}

}

public ClassLoader getClassLoaderForExtraModule() throws IOException {

List urls = new ArrayList(5);

//foreach( filepath: external file *.JAR) with each external file *.JAR, do as follows

File jar = new File(filepath);

JarFile jf = new JarFile(jar);

urls.add(jar.toURI().toURL());

Manifest mf = jf.getManifest(); // If the jar has a class-path in it's manifest add it's entries

if (mf

!= null) {

String cp =

mf.getMainAttributes().getValue("class-path");

if (cp

!= null) {

for (String cpe : cp.split("\\s+")) {

File lib =

new File(jar.getParentFile(), cpe);

urls.add(lib.toURI().toURL());

}

}

}

ClassLoader cl = ClassLoader.getSystemClassLoader();

if (urls.size() > 0) {

cl = new URLClassLoader(urls.toArray(new URL[urls.size()]), ClassLoader.getSystemClassLoader());

}

return cl;

}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值