如何从Java获取jar文件的主类名称?
我想使用 URLClassLoader 加载并执行外部 jar 文件。
从中获得“主级”的最简单方法是什么?
I want to load and execute external jar file using URLClassLoader.
What is the easiest way to get "Main-Class" from it?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我知道这是一个老问题,但至少对于 JDK 1.7,之前提出的解决方案似乎不起作用。
因此,我发布了我的:
其他解决方案对我不起作用的原因是因为
j.getManifest().getEntries()
结果不包含 Main-Class 属性,即而是包含在 getMainAttributes() 方法返回的列表中。I know this is an old question but, at least with the JDK 1.7, the previously proposed solutions did not seem to work.
For this reason I am posting mine:
The reason why the other solutions did not work for me was because
j.getManifest().getEntries()
turns out to not contain the Main-Class attribute, that was instead contained in the list returned by the getMainAttributes() method.来自此处 - 列出 jarfile 的主要属性
From here - Listing the main attributes of a jarfile
这只有在 jar 是自动执行的情况下才可能实现;在这种情况下,将使用
Main-Class:
键在清单文件中指定主类,此处提供了一些参考信息:
http://docs.oracle.com/javase/tutorial/deployment/ jar/appman.html
您需要下载 jarfile,然后使用
java.util.JarFile
访问它;一些java代码可能是:This will only be possible if the jar is self-executing; in which case the main class will be specified in the manifest file with the key
Main-Class:
Some reference information is provided here:
http://docs.oracle.com/javase/tutorial/deployment/jar/appman.html
You will need to download the jarfile then use
java.util.JarFile
to access it; some java code for this might be: