![](/img/trans.png)
[英]How to load jar files at runtime from a folder & instantiate classes in JBoss EAP 6.0.1
[英]How to load Classes at runtime from a folder or JAR?
我正在嘗試制作一個 Java 工具,它將掃描 Java 應用程序的結構並提供一些有意義的信息。 為此,我需要能夠從項目位置(JAR/WAR 或僅文件夾)掃描所有 .class 文件,並使用反射來了解它們的方法。 事實證明,這幾乎是不可能的。
我可以找到很多基於 URLClassloader 的解決方案,它們允許我從目錄/存檔中加載特定的類,但沒有一個允許我在沒有關於類名或包結構的任何信息的情況下加載類。
編輯:我想我的措辭很糟糕。 我的問題不是我不能獲得所有的類文件,我可以用遞歸等來做到這一點並正確定位它們。 我的問題是為每個類文件獲取一個 Class 對象。
以下代碼從 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
列出 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;
}
為此,我需要能夠從項目位置(JAR/WAR 或只是一個文件夾)掃描所有 .class 文件
掃描文件夾中的所有文件很簡單。 一種選擇是在表示文件夾的File
上調用File.listFiles()
,然后迭代生成的數組。 要遍歷嵌套文件夾的樹,請使用遞歸。
可以使用JarFile
API 掃描 JAR 文件的文件......並且您不需要遞歸遍歷嵌套的“文件夾”。
這些都不是特別復雜。 只需閱讀 javadoc 並開始編碼。
帶着類似的要求來到這里:
在某個包中有一些正在開發的服務類,它們實現了一個公共接口,並希望在運行時檢測它們。
部分問題是在特定包中查找類,其中應用程序可能是從 jar 文件或從包/文件夾結構中的解壓類加載的。
所以我把 amcgh 和一個匿名的解決方案放在一起。
// 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;
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.