---
title: "How to know the main class of a jar file?"
author: "willpower"
date: "2007-04-02T15:18:39Z"
tags: []
slug: "how-to-know-the-main-class-of-a-jar-file"
draft: false
lastmod: "2007-04-02T15:18:39Z"
id: 67375
url: "https://willpower.iteye.com/blog/67375"
---

Easy. Here is an implementation from Hadoop.

java 代码

01. /\**
02. * A micro-application that prints the main class name out of a jar file.
03. * @author Owen O'Malley
04. \*/
05. public class PrintJarMainClass {
06. /\**
07. * @param args
08. \*/
09. public static void main(String\[] args) {
10. try {
11. JarFile jar\_file = new JarFile(args\[0]);
12. if (jar\_file != null) {
13. Manifest manifest = jar\_file.getManifest();
14. if (manifest != null) {
15. String value = manifest.getMainAttributes().getValue("Main-Class");
16. if (value != null) {
17. System.out.println(value.replaceAll("/", "."));
18. return;
19. }
20. }
21. }
22. } catch (Throwable e) {
23. // ignore it
24. }
25. System.out.println("UNKNOWN");
26. System.exit(1);
27. }
28. }