[猜想]MANIFEST.MF只会在独立执行的jar文件中起作用,在被调用的jar文件中不起作用。一个运行的工程只能有一个MANIFEST.MF,所以当jar是被引入的方式来运行的,那么他的MANIFEST.MF无用。起作用的事宿主程序的MANIFEST.MF。

b.jar

com.B.jar

package com;

import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.Enumeration;
import java.util.jar.Attributes;
import java.util.jar.Manifest;


public class B {
    public void bbb() throws IOException {
        System.out.println("this is Class B!");
        Enumeration resEnum = Thread.currentThread().getContextClassLoader().getResources("META-INF/MANIFEST.MF");
        while (resEnum.hasMoreElements()) {
            try {
                URL url = (URL) resEnum.nextElement();
                InputStream is = url.openStream();
                String str = url.getPath();
                System.out.println("path:"+str);
                if (is != null) {
                    Manifest manifest = new Manifest(is);
                    Attributes mainAttribs = manifest.getMainAttributes();
                    String v = mainAttribs.getValue("Main-Class");
                    System.out.println("Main-Class:"+v);
                }
            } catch (Exception localException) {

            }
        }
    }
}

a.jar中引入b.jar

com.A.jar

package com;

import java.io.IOException;

import com.B;

public class A {
    public static void main(String[] args) {
        try {
            B b = new B();
            b.bbb();
        } catch (IOException e) {
            e.printStackTrace();
        }        
    }
}

运行a.jar

λ java -jar a.jar
this is Class B!
Main-Class:org.eclipse.jdt.internal.jarinjarloader.JarRsrcLoader
Main-Class:com.B

其实这个例子还是不能说明论证猜想。但是说明了一点jar文件的运行实际是将各个类连接起来,常用的是通过包来搜索需要的类,也可以通过写代码搜索需要的类的路径。

results matching ""

    No results matching ""