[英]How to load a class which implements a interface from a jar file at runtime?
I want to implement an application which could use users implemented classes. 我想实现一个可以使用用户实现的类的应用程序。 Each class should be implemented an interface that I define the interfaces and at last, all of classes which implemented by a user, archived in a jar file. 每个类都应实现一个我定义接口的接口,最后,由用户实现的所有类都应存储在jar文件中。 Users copy the jar files in to class path and then only give the jar file name to my application. 用户将jar文件复制到类路径中,然后仅将jar文件名提供给我的应用程序。 My application should be able to load jar file dynamically. 我的应用程序应该能够动态加载jar文件。 To do this I found this post that is very useful, but it loads classes by class names. 为此,我发现这篇文章非常有用,但是它通过类名加载类。 I want to load classes based on their parents. 我想根据他们的父母来上课。
public class A implements iA {
@Override
int getAValue() { ... }
}
public class B implements iB {
@Override
int getBValue() { ... }
}
Suppose loaded jar file has both A
and B
classes. 假设加载的jar文件同时具有A
和B
类。 I want to get an instance from class B
by knowing the iB
interface name. 我想通过了解iB
接口名称从类B
获取实例。
What should I do? 我该怎么办?
Check this post out: Find Java classes implementing an interface 看看这篇文章: 查找实现接口的Java类
It talks about the solution to what you want. 它讨论您想要的解决方案。
I know what I am going to suggest is not the lightest way to do it, but you just described one of the fundamental use cases for a plugin architecture in Java and the success story of OSGi. 我知道我要提出的建议并不是最简单的方法,但是您只是描述了Java插件体系结构的基本用例之一,以及OSGi的成功案例。
I would suggest using something light like Apache Felix, make the jar that the user provides implement a simple osgi.BundleActivator and register the implementation of your Interface as an OSGi service. 我建议您使用Apache Felix之类的工具,使用户提供的jar实现一个简单的osgi.BundleActivator,并将Interface的实现注册为OSGi服务。 (This is just a fancy hash map and nothing to do with REST services or the like). (这只是一个花哨的哈希图,与REST服务等无关)。
Then you can just obtain all the implementations of a given interface. 然后,您可以获取给定接口的所有实现。 Its pretty straight forward. 它非常简单。 You can check out the Felix documentation here: http://felix.apache.org/site/apache-felix-framework-launching-and-embedding.html 您可以在此处查看Felix文档: http : //felix.apache.org/site/apache-felix-framework-launching-and-embedding.html
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.