我正在使用Spring设计一个系统,其中一些用户应该能够实现一些类,提交JAR并能够执行他们的提交,前提是Jar内的类符合应该实现的接口。我们的想法是使用jar(以及一些xml配置文件)建立可扩展性框架。
我的问题是,这可能吗?我应该如何处理上述Jars的执行,是否可以在提交期间验证罐子的内容是否符合API?
谢谢!
答案 0 :(得分:1)
URLClassLoader child = new URLClassLoader (myJar.toURL(), this.getClass().getClassLoader());
Class classToLoad = Class.forName ("com.MyClass", true, child);
Method method = classToLoad.getDeclaredMethod ("myMethod");
Object instance = classToLoad.newInstance ();
Object result = method.invoke (instance);
How should I load Jars dynamically at runtime?
限制加载的jar的权限 Java security: Sandboxing plugins loaded via URLClassLoader
使用反射来测试类 How can I determine whether a Java class is abstract by reflection https://docs.oracle.com/javase/tutorial/reflect/
答案 1 :(得分:1)
我最终使用JCL:https://github.com/kamranzafar/JCL
我用这样的东西:
public class AnalyticsMethodsClassPathLoader {
private JarClassLoader jcl;
private JclObjectFactory factory;
public AnalyticsMethodsClassPathLoader(String analyticsMethodsJarsFolder) {
//JCL object for loading jars
jcl = new JarClassLoader();
//Loading classes from different sources
jcl.add(analyticsMethodsJarsFolder);
// Set ClassPathLoader priorities to prevent collisions when loading
jcl.getParentLoader().setOrder(1);
jcl.getLocalLoader().setOrder(2);
jcl.getSystemLoader().setOrder(3);
jcl.getThreadLoader().setOrder(4);
jcl.getCurrentLoader().setOrder(5);
// Set default to cglib (from version 2.2.1)
ProxyProviderFactory.setDefaultProxyProvider( new CglibProxyProvider() );
factory = JclObjectFactory.getInstance(true);
}
public AnalyticsMethod loadClass(String implementingClass) throws AnalyticsMethodLoaderException {
//Create object of loaded class
AnalyticsMethod abstractMethod;
try{
abstractMethod = (AnalyticsMethod) factory.create(jcl, implementingClass);
return abstractMethod;
}
catch (JclException e)
{
e.printStackTrace();
throw new AnalyticsMethodLoaderException("The class " + implementingClass +
" was not found or does not implement the framework.");
}
catch (java.lang.NoSuchMethodError error)
{
error.printStackTrace();
throw new AnalyticsMethodLoaderException("The class " + implementingClass +
" does not have an empty constructor.");
}
}
}
它相对稳定,允许我在春天做我需要的,而不需要将它与现在不支持的弹簧OSGi功能结合起来。 我知道它有局限性,并不是所有情况下的绝对最佳解决方案,但提交和执行简单的罐子工作得很好。