简体   繁体   English

带有URLClassLoader的ClassNotFound加载Jar

[英]ClassNotFound with URLClassLoader loading a Jar

Using the following code I get a ClassNotFoundException 使用以下代码,我得到一个ClassNotFoundException

File jarFile = new File(jar);
      URL jarUrl = new URL("jar", "", jarFile.getAbsolutePath() + "!/");

URLClassLoader loader = new URLClassLoader(
      new URL[] {jarUrl}, ClassLoader.getSystemClassLoader());

Class<? extends Animal> clazz =
      (Class<? extends Animal>)loader.loadClass("com.mycompany.dog.Dog");

The contents of the Jar are as follows: Jar的内容如下:

META-INF/ 
META-INF/MANIFEST.MF 
com/ 
com/mycompany/ 
com/mycompany/dog/ 
com/mycompany/dog/Dog$1.class 
com/mycompany/dog/Dog.class 
META-INF/maven/ 
META-INF/maven/com.mycompany.app/ 
META-INF/maven/com.mycompany.app/dog/ 
META-INF/maven/com.mycompany.app/dog/pom.xml 
META-INF/maven/com.mycompany.app/dog/pom.properties 
com/mycompany/app/ 
com/mycompany/app/Animal.class 
com/mycompany/app/ActionLog.class 
META-INF/maven/com.mycompany.app/animal/ 
META-INF/maven/com.mycompany.app/animal/pom.xml 
META-INF/maven/com.mycompany.app/animal/pom.properties

Am I doing something wrong? 难道我做错了什么?

I would not trust trying to create the Jar URL through the URL constructors, as it may differ from the URL produced by calling File.toURI().toURL() (which forms a valid URL). 我不信任尝试通过URL构造函数创建Jar URL,因为它可能与通过调用File.toURI().toURL() (形成有效URL)而产生的URL不同。

Here is an example. 这是一个例子。

import java.net.URL;
import java.io.File;

public class JarURL {

    public static void main(String[] args) throws Exception {
        File f = new File("C:\\the.jar");
        URL jarUrl1 = new URL("jar", "", f.getAbsolutePath() + "!/");
        URL jarUrl2 = f.toURI().toURL();
        System.out.println("jarUrl1: " + jarUrl1);
        System.out.println("jarUrl2: " + jarUrl2);
    }
}

Produces output: 产生输出:

jarUrl1: jar:C:\the.jar!/
jarUrl2: file:/C:/the.jar

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM