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

78

我正在尝试创建一个Java工具,可以扫描Java应用程序的结构并提供一些有意义的信息。为此,我需要能够从项目位置(JAR / WAR或仅文件夹)扫描所有.class文件,并使用反射读取有关其方法的信息。但这似乎是不可能的。

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

编辑: 我认为我表达得不好。我的问题不是我无法获取所有的class文件,我可以通过递归等方式做到并正确定位它们。我的问题是获得每个class文件的Class对象。


1
你如何加载一个类并忽略它的完全限定名?我认为这是不可能的。 - Edwin Dalorzo
4
下面的答案将帮助您找到类文件,但根据您的项目大小,使用asm或者javassist可能是值得的。这些工具可以让您在不将所有类加载到内存中的情况下分析它们。 - Nick Wilson
4个回答

125
以下代码从JAR文件中加载所有类。 它不需要了解有关这些类的任何信息。 类的名称是从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对象:

ClassPool cp = ClassPool.getDefault();
...
CtClass ctClass = cp.get(className);
从ctClass中,您可以获取所有的方法、字段、嵌套类......请查看javassist API: https://jboss-javassist.github.io/javassist/html/index.html

1
抱歉提起一个旧帖子(顺便感谢您的回答,它对我很有用)。然而,new URL("jar:file:" + pathToJar+"!/") 导致了 ClassNotFoundException。对我有效的是:URL[] urls = { new URL("jar:" + pathToJar+"!/") }; 不确定为什么?希望能帮助其他人。 - taylorcressy
1
不错。你可能想关闭jarFile吧?try { ... } finally { jarFile.close(); } - Stefan Reich
链接已失效,请有人修复! - RayanFar
@RayanFar:已修复 - Apfelsaft
7
使用String.valueOf(".class").length()可能比"- 6"更加直观表达意思。 - Mano
显示剩余3条评论

11

列出jar文件中的所有类。

public static List getClasseNames(String jarName) {
    ArrayList classes = new ArrayList();

    if (debug)
        System.out.println("Jar " + jarName );
    try {
        JarInputStream jarFile = new JarInputStream(new FileInputStream(
                jarName));
        JarEntry jarEntry;

        while (true) {
            jarEntry = jarFile.getNextJarEntry();
            if (jarEntry == null) {
                break;
            }
            if (jarEntry.getName().endsWith(".class")) {
                if (debug)
                    System.out.println("Found "
                            + jarEntry.getName().replaceAll("/", "\\."));
                classes.add(jarEntry.getName().replaceAll("/", "\\."));
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    return classes;
}

6
为了做到这一点,我需要能够扫描项目位置(JAR/WAR或只是文件夹)中的所有.class文件。
扫描文件夹中的所有文件很简单。一种选择是在表示文件夹的File上调用File.listFiles(),然后迭代生成的数组。要遍历嵌套文件夹的树,请使用递归。
使用JarFile API可以扫描JAR文件的文件...而且您不需要递归来遍历嵌套的“文件夹”。
这两者都不是特别复杂的。只需阅读javadoc并开始编码即可。

2
带着类似的需求来到了这里:

在某个包中有越来越多的服务类,它们实现了一个共同的接口,并希望在运行时检测到它们。

问题的一部分是找到特定包中的类,应用程序可能从jar文件或包/文件夹结构中加载。
因此,我将amicngh和anonymous的解决方案结合起来。
// Retrieve classes of a package and it's nested package from file based class repository

package esc;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
import java.util.jar.JarEntry;
import java.util.jar.JarInputStream;

public class GetClasses
{
    private static boolean debug = false;
    
    /**
     * test function with assumed package esc.util
     */
    public static void main(String... args)
    {
        try
        {
            final Class<?>[] list = getClasses("esc.util");
            for (final Class<?> c : list)
            {
                System.out.println(c.getName());
            }
        }
        catch (final IOException e)
        {
            e.printStackTrace();
        }
    }

    /**
     * Scans all classes accessible from the context class loader which belong to the given package and subpackages.
     *
     * @precondition Thread Class loader attracts class and jar files, exclusively
     * @precondition Classes with static code sections are executed, when loaded and thus must not throw exceptions
     *
     * @param packageName
     *            [in] The base package path, dot-separated
     *
     * @return The classes of package /packageName/ and nested packages
     *
     * @throws IOException,
     *             ClassNotFoundException not applicable
     *
     * @author Sam Ginrich, http://www.java2s.com/example/java/reflection/recursive-method-used-to-find-all-classes-in-a-given-directory-and-sub.html
     *
     */
    public static Class<?>[] getClasses(String packageName) throws IOException
    {
        final ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
        assert classLoader != null;
        if (debug)
        {
            System.out.println("Class Loader class is " + classLoader.getClass().getName());
        }
        final String packagePath = packageName.replace('.', '/');
        final Enumeration<URL> resources = classLoader.getResources(packagePath);
        final List<Class<?>> classes = new ArrayList<Class<?>>();
        while (resources.hasMoreElements())
        {
            final URL resource = resources.nextElement();
            final String proto = resource.getProtocol();
            if ("file".equals(proto))
            {
                classes.addAll(findFileClasses(new File(resource.getFile()), packageName));
            }
            else if ("jar".equals(proto))
            {
                classes.addAll(findJarClasses(resource));
            }
            else
            {
                System.err.println("Protocol " + proto + " not supported");
                continue;
            }
        }
        return classes.toArray(new Class[classes.size()]);
    }

    
    /**
     * Linear search for classes of a package from a jar file
     *
     * @param packageResource
     *            [in] Jar URL of the base package, i.e. file URL bested in jar URL
     *
     * @return The classes of package /packageResource/ and nested packages
     *
     * @throws -
     *
     * @author amicngh, Sam Ginrich@stackoverflow.com
     */
    private static List<Class<?>> findJarClasses(URL packageResource)
    {
        final List<Class<?>> classes = new ArrayList<Class<?>>();
        try
        {
            System.out.println("Jar URL Path is " + packageResource.getPath());
            final URL fileUrl = new URL(packageResource.getPath());
            final String proto = fileUrl.getProtocol();
            if ("file".equals(proto))
            {
                final String filePath = fileUrl.getPath().substring(1); // skip leading /
                final int jarTagPos = filePath.indexOf(".jar!/");
                if (jarTagPos < 0)
                {
                    System.err.println("Non-conformant jar file reference " + filePath + " !");
                }
                else
                {
                    final String packagePath = filePath.substring(jarTagPos + 6);
                    final String jarFilename = filePath.substring(0, jarTagPos + 4);
                    if (debug)
                    {
                        System.out.println("Package " + packagePath);
                        System.out.println("Jar file " + jarFilename);
                    }
                    final String packagePrefix = packagePath + '/';
                    try
                    {
                        final JarInputStream jarFile = new JarInputStream(
                                new FileInputStream(jarFilename));
                        JarEntry jarEntry;

                        while (true)
                        {
                            jarEntry = jarFile.getNextJarEntry();
                            if (jarEntry == null)
                            {
                                break;
                            }
                            final String classPath = jarEntry.getName();
                            if (classPath.startsWith(packagePrefix) && classPath.endsWith(".class"))
                            {
                                final String className = classPath
                                        .substring(0, classPath.length() - 6).replace('/', '.');

                                if (debug)
                                {
                                    System.out.println("Found entry " + jarEntry.getName());
                                }
                                try
                                {
                                    classes.add(Class.forName(className));
                                }
                                catch (final ClassNotFoundException x)
                                {
                                    System.err.println("Cannot load class " + className);
                                }
                            }
                        }
                        jarFile.close();
                    }
                    catch (final Exception e)
                    {
                        e.printStackTrace();
                    }
                }
            }
            else
            {
                System.err.println("Nested protocol " + proto + " not supprted!");
            }
        }
        catch (final MalformedURLException e)
        {
            e.printStackTrace();
        }
        return classes;
    }

    /**
     * Recursive method used to find all classes in a given directory and subdirs.
     *
     * @param directory
     *            The base directory
     * @param packageName
     *            The package name for classes found inside the base directory
     * @return The classes
     * @author http://www.java2s.com/example/java/reflection/recursive-method-used-to-find-all-classes-in-a-given-directory-and-sub.html
     * @throws -
     *
     */
    private static List<Class<?>> findFileClasses(File directory, String packageName)
    {
        final List<Class<?>> classes = new ArrayList<Class<?>>();
        if (!directory.exists())
        {
            System.err.println("Directory " + directory.getAbsolutePath() + " does not exist.");
            return classes;
        }
        final File[] files = directory.listFiles();
        if (debug)
        {
            System.out.println("Directory "
                    + directory.getAbsolutePath()
                    + " has "
                    + files.length
                    + " elements.");
        }
        for (final File file : files)
        {
            if (file.isDirectory())
            {
                assert !file.getName().contains(".");
                classes.addAll(findFileClasses(file, packageName + "." + file.getName()));
            }
            else if (file.getName().endsWith(".class"))
            {
                final String className = packageName
                        + '.'
                        + file.getName().substring(0, file.getName().length() - 6);
                try
                {
                    classes.add(Class.forName(className));
                }
                catch (final ClassNotFoundException cnf)
                {
                    System.err.println("Cannot load class " + className);
                }
            }
        }
        return classes;
    }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接