当前位置:   article > 正文

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

fat 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;

}

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/人工智能uu/article/detail/770337
推荐阅读
相关标签
  

闽ICP备14008679号