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

编程入门 行业动态 更新时间:2024-10-27 21:17:22
本文介绍了如何在运行时从文件夹或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: www.csg.ci.i.u-tokyo.ac.jp/~chiba/javassist/html/index.html

更多推荐

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

本文发布于:2023-11-13 09:16:02,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1583982.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:文件夹   加载   如何在   JAR

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!