如何在运行时从文件夹或JAR加载类? [英] How to load Classes at runtime from a folder or JAR?

查看:151
本文介绍了如何在运行时从文件夹或JAR加载类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图创建一个Java工具,它将扫描Java应用程序的结构并提供一些有意义的信息。要做到这一点,我需要能够从项目位置(JAR / WAR或只是一个文件夹)扫描所有的.class文件,并使用反射读取他们的方法。这证明是几乎不可能的。

I am trying to make a Java tool that will scan the structure of a Java application and provide some meaningful information. To do this, I need to be able to scan all of the .class files from the project location (JAR/WAR or just a folder) and use reflection to read about their methods. This is proving to be near impossible.

我可以找到很多基于URLClassloader的解决方案,允许我从目录/存档加载特定的类,但没有一个允许我加载类,而没有关于类名或包结构的任何信息。

I can find a lot of solutions based on URLClassloader that allow me to load specific classes from a directory/archive, but none that will allow me to load classes without having any information about the class name or package structure.

编辑:
我认为我写得很差。我的问题不是我不能得到所有的类文件,我可以做递归等,并找到它们正确。我的问题是获取每个类文件的Class对象。

I think I phrased this poorly. My issue is not that I can't get all of the class files, I can do that with recursion etc. and locate them properly. My issue is obtaining a Class object for each class file.

推荐答案

以下代码从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:
http ://www.csg.ci.iu-tokyo.ac.jp/~chiba/javassist/html/index.html

From the ctClass, you can get all methods, fields, nested classes, .... Take a look at the javassist api: http://www.csg.ci.i.u-tokyo.ac.jp/~chiba/javassist/html/index.html

这篇关于如何在运行时从文件夹或JAR加载类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆