尽管我的课程已加载,但Class.forName会引发ClassNotFoundException [英] Though my class was loaded, Class.forName throws ClassNotFoundException
问题描述
代码如下
它所做的是将所有类加载到我放置在主目录中的jar文件中.
what it does is it loads all the classes inside a jar file which I placed inside my home directory .
import java.io.File;
import java.util.jar.JarFile;
import java.util.jar.JarEntry;
import java.net.URLClassLoader;
import java.net.URL;
import java.util.Enumeration;
import java.lang.ClassLoader;
public class Plugin extends ClassLoader {
public static void main(String[] args) throws Exception {
File file = new File(System.getProperty("user.home") + "/HelloWorld.jar");
URLClassLoader clazzLoader = URLClassLoader.newInstance(new URL[]{file.toURI().toURL()});
JarFile jarFile = new JarFile(file);
Enumeration<JarEntry> entries = jarFile.entries();
while (entries.hasMoreElements()) {
JarEntry element = entries.nextElement();
if (element.getName().endsWith(".class")) {
try {
Class c = clazzLoader.loadClass(element.getName().replaceAll(".class", "").replaceAll("/", "."));
c.newInstance(); // this proves that class is loaded
} catch (Exception e) {
e.printStackTrace();
}
}
}
Class cls = Class.forName("HelloWorld");
cls.newInstance();
Plugin p = new Plugin();
p.checkIfLoaded();
}
public void checkIfLoaded() {
System.out.println("coming in");
if (findLoadedClass("HelloWorld") != null){
System.out.println("Yepee, HelloWorld class is loaded !");
}
}
}
我的HelloWorld与 https://github.com/HarishAtGitHub/doc/blob/master/makeExecutableJar/HelloWorld.java
My HelloWorld is as in https://github.com/HarishAtGitHub/doc/blob/master/makeExecutableJar/HelloWorld.java
然后按照上面提到的我的github帐户中的说明获取jar.
and the jar is got using the instructions in my github account mentioned above .
c.newInstance()
有效.
我如何确认?
静态块被执行了...
the static block got executed ...
但是Class.forName("HelloWorld")
抛出ClassNotFoundException
还findLoadedClass("HelloWorld"
)为null ..
also findLoadedClass("HelloWorld"
) is null ..
我不明白为什么会有这种奇怪的行为?
I cannot understand why this strange behaviour ?
请指导...
推荐答案
这是类加载器问题.
As per the Javadocs to Class.forName
, you are looking up the class using the classloader of the current class. As your main class, this will be the JVM's bootstrap classloader (and will more or less just include the standard library plus anything you provided as a -cp
command line argument). It is not going to delegate to the classloader that you instantiated as a local variable, and so will not return classes that that classloader could find.
如果要明确指定类加载器,然后调用
If you were to specify the classloader explicitly, and call
Class.forName("HelloWorld", true, clazzloader)
然后将搜索刚刚创建的类加载器,并应找到您的类.
then the classloader you just created will be searched instead and your class should be found.
这篇关于尽管我的课程已加载,但Class.forName会引发ClassNotFoundException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!