您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

Java 读我自己的Jar清单

Java 读我自己的Jar清单

你可以执行以下两项操作之一:

调用getResources()并遍历返回的URL集合,将它们作为清单读取,直到找到你的URL:

Enumeration<URL> resources = getClass().getClassLoader()
  .getResources("Meta-INF/MANIFEST.MF");
while (resources.hasMoreElements()) {
    try {
      Manifest manifest = new Manifest(resources.nextElement().openStream());
      // check that this is your manifest and do what you need or get the next one
      ...
    } catch (IOException E) {
      // handle
    }
}

你可以尝试检查是否getClass().getClassLoader()是的实例java.net.urlclassloader。Sun的大多数类加载器包括AppletClassLoader。然后,你可以对其进行转换并调用findResource()已知的(至少对于applet而言)直接返回所需的清单:

urlclassloader cl = (urlclassloader) getClass().getClassLoader();
try {
  URL url = cl.findResource("Meta-INF/MANIFEST.MF");
  Manifest manifest = new Manifest(url.openStream());
  // do stuff with it
  ...
} catch (IOException E) {
  // handle
}

你可以先找到课程的URL。如果是JAR,则从那里加载清单。例如,

Class clazz = MyClass.class;
String className = clazz.getSimpleName() + ".class";
String classPath = clazz.getResource(className).toString();
if (!classPath.startsWith("jar")) {
  // Class not from JAR
  return;
}
String manifestPath = classPath.substring(0, classPath.lastIndexOf("!") + 1) + 
    "/Meta-INF/MANIFEST.MF";
Manifest manifest = new Manifest(new URL(manifestPath).openStream());
Attributes attr = manifest.getMainAttributes();
String value = attr.getValue("Manifest-Version");
java 2022/1/1 18:18:42 有627人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶