代码如下
它的作用是将所有类加载到我放置在主目录中的 jar 文件中。
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
jar 是使用上面提到的我的 github 帐户中的说明获得的。
c.newInstance()
作品。
我是怎么确认的?
静态块被执行了......
但Class.forName("HelloWorld")
抛出ClassNotFoundException
也findLoadedClass("HelloWorld"
) 为空..
我不明白为什么会出现这种奇怪的行为?
请指导...