English 中文(简体)
多个 JARs 的动态类装入
原标题:Dynamic class loading from multiple JARs

考虑以下简单方法,即(试图)装入特定名称的所有类别,存放在位于指定路径(即:)的JAR文件内。

public static List<Class<?>> getAllClasses(String name, String path)
{
    File file = new File(path);

    try
    {
        URL url = file.toURI().toURL();

        URLClassLoader loader = URLClassLoader.newInstance(new URL[] {url});

        JarFile jar = new JarFile(file);

        Enumeration<JarEntry> entries = jar.entries();

        Class<?> type;

        String elementName;

        List<Class<?>> classList = new ArrayList<Class<?>>();

        while (entries.hasMoreElements())
        {
            elementName = entries.nextElement().getName();

            if (elementName.equals(name))
            {
                try
                {
                    type = loader.loadClass(elementName);
                    classList.add(type);
                }
                catch (Exception e)
                {
                }
            }
        }

        return classList;
    }
    catch (Exception e)
    {
    }

    return null;
}

如果路径中有超过1个 JARs, 每一个都至少有1个类别, 名称相同, 带有已经装入的类, 例如 org. whatever. myClass , 是否有办法, 没有定制的分类装载器, 可以装入全部 org. whatever. MyClass 类?

最佳回答

标准级装载器在单个名称空间中装载类。如果您正在寻找不同版本执行中的相同类, 那么您必须使用自定义级装载器。 您的代码片断是自定义装入的示例 。

请参看发表于这里。

问题回答

类不能只装入一次, 而类的密钥是类装入器+Fully 定性类名称。 它会检查缓存和类装载器链, 如果发现该类, 它将不再尝试再装入它。 被选中的密钥是具体执行 。





相关问题
Spring Properties File

Hi have this j2ee web application developed using spring framework. I have a problem with rendering mnessages in nihongo characters from the properties file. I tried converting the file to ascii using ...

Logging a global ID in multiple components

I have a system which contains multiple applications connected together using JMS and Spring Integration. Messages get sent along a chain of applications. [App A] -> [App B] -> [App C] We set a ...

Java Library Size

If I m given two Java Libraries in Jar format, 1 having no bells and whistles, and the other having lots of them that will mostly go unused.... my question is: How will the larger, mostly unused ...

How to get the Array Class for a given Class in Java?

I have a Class variable that holds a certain type and I need to get a variable that holds the corresponding array class. The best I could come up with is this: Class arrayOfFooClass = java.lang....

SQLite , Derby vs file system

I m working on a Java desktop application that reads and writes from/to different files. I think a better solution would be to replace the file system by a SQLite database. How hard is it to migrate ...

热门标签