如何在运行时加载jar文件的所有类?
根据这个问题,可以通过以下方式从jar文件加载类:
ClassLoader loader = URLClassLoader.newInstance(
new URL[] { jarFileURL },
getClass().getClassLoader()
);
Class<?> clazz = Class.forName("mypackage.MyClass", true, loader);
How to load all< /strong> jar 文件中包含的类?
According to this question, it is possible to load a class from a jar file with:
ClassLoader loader = URLClassLoader.newInstance(
new URL[] { jarFileURL },
getClass().getClassLoader()
);
Class<?> clazz = Class.forName("mypackage.MyClass", true, loader);
How to load all classes contained in a jar file?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
类加载器将在需要时立即加载 .class 文件。如果不需要,则不会加载。
为什么您认为您的方法将比类加载器已有的方法有所改进?
The class loader will load a .class file as soon as it's needed. If it's not needed, it won't be loaded.
Why do you think that your approach will be an improvement over what the class loader already does?
您必须将其作为 zip 文件打开,浏览名称,假设所有以
.class
结尾的条目都是类文件并加载它们,忽略嵌套类等。但为什么?
You will have to open it as zip file, go through the names, assume all entries ending in
.class
are class files and load them, ignoring nested classes and such.But....why?
如果您确实想动态地读取类,请将其留给已经实现了该功能的专业人士。实现自己的类加载器很困难。相信我。我已经尝试过几次了。请改用 OSGi 之类的东西,它可以为您提供动态类加载等功能。
If you really want to read classes dynamically, leave that to the pros, who already implemented that. Implementing your own classloader is hard. Believe me. I already tried a few times. Use something like OSGi instead, which provides you dynamic class loading and much more.