[英]How to load an implementation class from a specific jar
I have an URLClassLoader
that contains several jars. 我有一个
URLClassLoader
,其中包含几个jar。 Normally, I would then use the ServiceLoader
to find implementations. 通常,然后我将使用
ServiceLoader
查找实现。
But now I need to find implementations in only one of these jars, but I still want to use this class loader. 但是现在我只需要在其中一个jar中找到实现,但是我仍然想使用此类加载器。 How can I do this?
我怎样才能做到这一点?
Since the ServiceLoader
does not provide this, you have to do it manually. 由于
ServiceLoader
不提供此功能,因此您必须手动进行操作。
public static <S> Iterable<S> getService(
File jar, ClassLoader loader, Class<S> service) {
ArrayList<S> list=new ArrayList<>();
String name=service.getName();
try(JarFile f=new JarFile(jar)) {
JarEntry entry = f.getJarEntry("META-INF/services/"+name);
if(entry==null) return Collections.emptyList();
try(BufferedReader r=new BufferedReader(new InputStreamReader(
f.getInputStream(entry), "UTF-8"))) {
Matcher m=Pattern.compile(
"[ \\t]*(\\p{javaJavaIdentifierStart}[\\p{javaJavaIdentifierPart}.]*)?[ \t]*(?:#.*)?")
.matcher("");
for(String s=""; s != null; s=r.readLine()) {
if(s.trim().length()==0) continue;
if(m.reset(s).matches()) {
String found=m.group(1);
if(found!=null) try {
list.add(loader.loadClass(found).asSubclass(service).newInstance());
}
catch(Throwable e) {
log(Level.SEVERE, found, e);
return null;
}
} else log(Level.WARNING, "malformed spi decl: {0}", s);
}
}
} catch(IOException ex) {
log(Level.SEVERE, name, ex);
return Collections.emptyList();
}
return list;
}
static void log(Level level, String msg, Throwable thrown)
{
Logger.getLogger("insert logger name here").log(level, msg, thrown);
}
static void log(Level level, String msg, Object arg)
{
Logger.getLogger("insert logger name here").log(level, msg, arg);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.