且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在运行时从文件夹或 JAR 加载类?

更新时间:2023-09-29 22:28:52

以下代码从 JAR 文件加载所有类.它不需要了解有关类的任何信息.类的名称是从 JarEntry 中提取的.

The following code loads all classes from a JAR file. It does not need to know anything about the classes. The names of the classes are extracted from the JarEntry.

JarFile jarFile = new JarFile(pathToJar);
Enumeration<JarEntry> e = jarFile.entries();

URL[] urls = { new URL("jar:file:" + pathToJar+"!/") };
URLClassLoader cl = URLClassLoader.newInstance(urls);

while (e.hasMoreElements()) {
    JarEntry je = e.nextElement();
    if(je.isDirectory() || !je.getName().endsWith(".class")){
        continue;
    }
    // -6 because of .class
    String className = je.getName().substring(0,je.getName().length()-6);
    className = className.replace('/', '.');
    Class c = cl.loadClass(className);

}

正如上面评论中所建议的,javassist 也是一种可能性.在while循环之前的某个地方初始化一个ClassPool形成上面的代码,而不是用类加载器加载类,你可以创建一个CtClass对象:

As suggested in the comments above, javassist would also be a possibility. Initialize a ClassPool somewhere before the while loop form the code above, and instead of loading the class with the class loader, you could create a CtClass object:

ClassPool cp = ClassPool.getDefault();
...
CtClass ctClass = cp.get(className);

从 ctClass 中,您可以获取所有方法、字段、嵌套类、....看一下javassist api:https://jboss-javassist.github.io/javassist/html/index.html

From the ctClass, you can get all methods, fields, nested classes, .... Take a look at the javassist api: https://jboss-javassist.github.io/javassist/html/index.html