如何从jar文件加载类并将其存储在arraylist中 [英] how to load classes from a jar file and store it in an arraylist

查看:138
本文介绍了如何从jar文件加载类并将其存储在arraylist中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从exchanges.jar文件加载类文件(没有实现任何通用接口)并将其存储在arraylist中
以前,我加载了.class文件(实现了一个通用接口) )从目录中使用

I am trying to load the class files(which do not implement any common interface) from the exchanges.jar file and store it in an arraylist Previously, i loaded the .class files(which implements a common interface) from a directory using

package edu.uh.cs.assign2;

import java.io.File;
import java.util.ArrayList;

import edu.uh.cs.iexchangeservices.IExchange;

public class ExchangeManager {
    private ArrayList<IExchange> exchangeList = new ArrayList<IExchange>();

    public ArrayList<IExchange> findClasses() throws Exception {

        File classDirectoryPath = new File(Thread.currentThread()
                .getContextClassLoader()
                .getResource("exchangeservices".replace('.', '/')).getFile());

        return loadExchangeClasses(classDirectoryPath);
    }

    public ArrayList<IExchange> loadExchangeClasses(File classDirectoryPath)
            throws Exception {

        if (!classDirectoryPath.exists())
            throw new LoadExchangesException("path not found");

        String[] exchangeClasses = classDirectoryPath.list();

        for (String exchangeClass : exchangeClasses) {

            if (exchangeClass.endsWith(".class")) {
                Object object = (IExchange) Class.forName(
                        "exchangeservices"
                                + '.'
                                + exchangeClass.substring(0,
                                        exchangeClass.length() - 6))
                        .newInstance();

                if (object instanceof IExchange)
                    exchangeList.add((IExchange) object);
            }
        }
        return exchangeList;
    }

}


推荐答案

我假设您要做的是加载位于JAR文件或任何其他URL中的一组类,然后返回包含这些类对象的列表。

I will assume that what you want to do is to load a set of classes located in a JAR file or any other URL, then return a list containing those class objects.

我的推荐是:


  • 使用类 java.util.jar.JarFile 读取jar中的所有条目。

  • 迭代条目,如果给定条目属于某个类(其名称以.class结尾),则加载class并将其添加到已加载类的列表中。

  • Use the class java.util.jar.JarFile to read all entries in your jar.
  • Iterate over the entries, and if a given entry belongs to a class (its name ends with ".class") then you load the class and add it to a list of loaded classes.

有点像这样:

JarFile jar = new JarFile(jarFile);
for(JarEntry entry: Collections.list(jar.entries())){
   if(entry.getName().endsWith(".class")){
     String className = entry.getName().replace("/", ".").replace(".class","");
     foundClasses.add(loader.loadClass(className));
    }
}

出于装载目的,您可以使用 java.net.URLClassLoader 包含你的jar文件。

For loading purposes you can use a java.net.URLClassLoader containing your jar file.

有点像这样

File jarFile = new File("./jedis.jar");
URLClassLoader loader = new URLClassLoader(new URL[]{jarFile.toURI().toURL()});

您将最终获得 foundClasses list。

You will end up with all the loaded classes in the foundClasses list.

另一方面,如果您确切知道要加载的类,那么URLClassLoader应该足以解决问题。

On the other hand, if you know exactly the classes that you want to load, then the URLClassLoader should suffice to solve the problem.

File jarFile = new File("./jedis.jar");
URLClassLoader loader = new URLClassLoader(new URL[]{jarFile.toURI().toURL()});
foundClasses.add(loader.loadClass("jedi.academy.ObiWan"));
foundClasses.add(loader.loadClass("jedi.academy.Luke"));
foundClasses.add(loader.loadClass("jedi.academy.Anakin"));

如果您希望此辅助类加载器独立于系统类加载器,请确保设置父级实例化URLClassLoader时类加载器为null:

If you want that this secondary class loader be independent of the system class loader make sure to set the parent class loader to null when instantiating the URLClassLoader:

URLClassLoader loader = new URLClassLoader(new URL[]{jarFile.toURI().toURL()}, null);

这篇关于如何从jar文件加载类并将其存储在arraylist中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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