How do you create a MANIFEST.MF that's available when you're testing and running from a jar in production?

前端 未结 9 1057
失恋的感觉
失恋的感觉 2020-12-28 16:28

I\'ve spent far too much time trying to figure this out. This should be the simplest thing and everyone who distributes Java applications in jars must have to deal with it.

9条回答
  •  梦谈多话
    2020-12-28 17:21

    You can get the manifest for an arbitrary class in an arbitrary jar without parsing the class url (which could be brittle). Just locate a resource that you know is in the jar you want, and then cast the connection to JarURLConnection.

    If you want the code to work when the class is not bundled in a jar, add an instanceof check on the type of URL connection returned. Classes in an unpacked class hierarchy will return a internal Sun FileURLConnection instead of the JarUrlConnection. Then you can load the Manifest using one of the InputStream methods described in other answers.

    @Test
    public void testManifest() throws IOException {
        URL res = org.junit.Assert.class.getResource(org.junit.Assert.class.getSimpleName() + ".class");
        JarURLConnection conn = (JarURLConnection) res.openConnection();
        Manifest mf = conn.getManifest();
        Attributes atts = mf.getMainAttributes();
        for (Object v : atts.values()) {
            System.out.println(v);
        }
    }
    

提交回复
热议问题