java 从jar包中或者指定路径下加载Class类

   最近有一个需求就是从指定路径下加载jar中或者指定路径下class文件到虚拟机中供SpringIoc 容器动态注入。
   寻找了一些资料并将成果分享出来

从jar 中加载class文件示例

public static void searchClass(String filePath) throws MalformedURLException, NoSuchMethodException {
        // 系统类库路径
        File libPath = new File(filePath);

        // 获取所有的.jar和.zip文件
        File[] jarFiles = libPath.listFiles(new FilenameFilter() {
            @Override
            public boolean accept(File dir, String name) {
                return name.endsWith(".jar") || name.endsWith(".zip");
            }
        });

        if (jarFiles != null) {
            // 从URLClassLoader类中获取类所在文件夹的方法
            // 对于jar文件,可以理解为一个存放class文件的文件夹
            Method method = URLClassLoader.class.getDeclaredMethod("addURL", URL.class);
            // 获取方法的访问权限
            boolean accessible = method.isAccessible();
            try {
                // 设置方法的访问权限
                if (accessible == false) {
                    method.setAccessible(true);
                }
                // 获取系统类加载器
                URLClassLoader classLoader = (URLClassLoader) ClassLoader.getSystemClassLoader();
                for (File file : jarFiles) {
                    URL url = file.toURI().toURL();
                    try {
                        method.invoke(classLoader, url);
                        log.debug("读取jar文件[name={}]", file.getName());
                    } catch (Exception e) {
                        log.error("读取jar文件[name={}]失败", file.getName());
                    }
                }
            } finally {
                method.setAccessible(accessible);
            }
        }
    }

从指定路径下获取class类文件

/**
     * 加载指定路径下所有Class文件
     * @param classPath
     */
    public static void searchClassInPath(String classPath) throws NoSuchMethodException, MalformedURLException {
        // 设置class文件所在根路径
        // 例如/usr/java/classes下有一个test.App类,则/usr/java/classes即这个类的根路径,
        // 而.class文件的实际位置是/usr/java/classes/test/App.class
        File clazzPath = new File(classPath);

        // 记录加载.class文件的数量
        int clazzCount = 0;

        if (clazzPath.exists() && clazzPath.isDirectory()) {
            // 获取路径长度
            int clazzPathLen = clazzPath.getAbsolutePath().length() + 1;

            Stack<File> stack = new Stack<>();
            stack.push(clazzPath);

            // 遍历类路径
            while (stack.isEmpty() == false) {
                File path = stack.pop();
                File[] classFiles = path.listFiles(new FileFilter() {
                    @Override
                    public boolean accept(File pathname) {
                        return pathname.isDirectory() || pathname.getName().endsWith(".class");
                    }
                });
                for (File subFile : classFiles) {
                    if (subFile.isDirectory()) {
                        stack.push(subFile);
                    } else {
                        if (clazzCount++ == 0) {
                            Method method = URLClassLoader.class.getDeclaredMethod("addURL", URL.class);
                            boolean accessible = method.isAccessible();
                            try {
                                if (accessible == false) {
                                    method.setAccessible(true);
                                }
                                // 设置类加载器
                                URLClassLoader classLoader = (URLClassLoader) ClassLoader.getSystemClassLoader();
                                // 将当前类路径加入到类加载器中
                                method.invoke(classLoader, clazzPath.toURI().toURL());
                            } catch (IllegalAccessException e) {
                                e.printStackTrace();
                            } catch (InvocationTargetException e) {
                                e.printStackTrace();
                            } finally {
                                method.setAccessible(accessible);
                            }
                        }
                        // 文件名称
                        String className = subFile.getAbsolutePath();
                        className = className.substring(clazzPathLen, className.length() - 6);
                        className = className.replace(File.separatorChar, '.');
                        // 加载Class类
                        try {
                           Class.forName(className);
                        } catch (ClassNotFoundException e) {
                            log.error("ClassNotFoundException {}",e);
                        }
                        log.info("读取应用程序类文件[class={}]", className);
                    }
                }
            }
        }
    }

加载指定路径下Class类文件

/**
     * 加载指定类路径下指定文件名
     * @param classPath
     */
    public static void searchClassByClassName(String classPath,String fullClassName) throws NoSuchMethodException, MalformedURLException {
        // 设置class文件所在根路径
        // 例如/usr/java/classes下有一个test.App类,则/usr/java/classes即这个类的根路径,
        // 而.class文件的实际位置是/usr/java/classes/test/App.class
        File clazzPath = new File(classPath);

        // 记录加载.class文件的数量
        int clazzCount = 0;

        if (clazzPath.exists() && clazzPath.isDirectory()) {
            // 获取路径长度
            int clazzPathLen = clazzPath.getAbsolutePath().length() + 1;

            Stack<File> stack = new Stack<>();
            stack.push(clazzPath);

            // 遍历类路径
            while (stack.isEmpty() == false) {
                File path = stack.pop();
                File[] classFiles = path.listFiles(new FileFilter() {
                    @Override
                    public boolean accept(File pathname) {
                        return pathname.isDirectory() || pathname.getName().endsWith(".class");
                    }
                });
                for (File subFile : classFiles) {
                    if (subFile.isDirectory()) {
                        stack.push(subFile);
                    } else {
                        if (clazzCount++ == 0) {
                            Method method = URLClassLoader.class.getDeclaredMethod("addURL", URL.class);
                            boolean accessible = method.isAccessible();
                            try {
                                if (accessible == false) {
                                    method.setAccessible(true);
                                }
                                // 设置类加载器
                                URLClassLoader classLoader = (URLClassLoader) ClassLoader.getSystemClassLoader();
                                // 将当前类路径加入到类加载器中
                                method.invoke(classLoader, clazzPath.toURI().toURL());
                            } catch (IllegalAccessException e) {
                                e.printStackTrace();
                            } catch (InvocationTargetException e) {
                                e.printStackTrace();
                            } finally {
                                method.setAccessible(accessible);
                            }
                        }
                        // 文件名称
                        String className = subFile.getAbsolutePath();
                        className = className.substring(clazzPathLen, className.length() - 6);
                        className = className.replace(File.separatorChar, '.');
                        // 加载Class类
                        try {

                            if (className.equals(fullClassName)){
                                Class.forName(className);
                                break;
                            }
                        } catch (ClassNotFoundException e) {
                            log.error("ClassNotFoundException {}",e);
                        }
                        log.info("读取应用程序类文件[class={}]", className);
                    }
                }
            }
        }
    }

参考文献:https://blog.csdn.net/mousebaby808/article/details/31788325

  • 3
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
要读取指定jar包,可以使用Java的反射机制。首需要使用Java加载器来加载指定jar包,然后使用反射机制来获取该jar包的所有。 以下是读取指定jar包所有的示例代码: ```java import java.io.File; import java.io.IOException; import java.net.URL; import java.net.URLClassLoader; import java.util.Enumeration; import java.util.jar.JarEntry; import java.util.jar.JarFile; public class JarReader { public static void main(String[] args) throws IOException, ClassNotFoundException { // 指定jar包路径 String jarPath = "path/to/your/jar/file.jar"; // 创建URLClassLoader来加载指定jar包 URL[] urls = { new URL("file:" + jarPath) }; ClassLoader cl = new URLClassLoader(urls); // 创建JarFile来读取jar包的内容 JarFile jarFile = new JarFile(new File(jarPath)); // 遍历jar包的所有 Enumeration<JarEntry> entries = jarFile.entries(); while (entries.hasMoreElements()) { JarEntry entry = entries.nextElement(); if (entry.getName().endsWith(".class")) { // 使用Class.forName方法来加载 Class<?> clazz = cl.loadClass(entry.getName().replaceAll("/", ".").replaceAll(".class", "")); // 处理获取到的,例如获取的方法和属性 // ... } } // 关闭JarFile jarFile.close(); } } ``` 在这个示例代码,我们首指定了要读取的jar包路径,然后创建了一个URLClassLoader来加载jar包。接着使用JarFile来读取jar包的内容,并遍历所有的。对于每个,使用Class.forName方法来加载,并处理获取到的,例如获取的方法和属性。 需要注意的是,这个示例代码只是演示了如何读取指定jar包的所有,并没有对获取到的进行实际的处理。实际使用时,需要根据具体的需求来处理获取到的

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值