要从实现特定接口的 jar 文件中动态加载类,但您事先不知道将是哪个类,并且 jar 文件本身没有指定任何默认的“插件”类,您可以遍历下载的 jar 并获取 jar 中包含的类列表,如下所示:
/**
* Scans a JAR file for .class-files and returns a {@link List} containing
* the full name of found classes (in the following form:
* packageName.className)
*
* @param file
* JAR-file which should be searched for .class-files
* @return Returns all found class-files with their full-name as a List of
* Strings
* @throws IOException If during processing of the Jar-file an error occurred
* @throws IllegalArgumentException If either the provided file is null, does
* not exist or is no Jar file
*/
public List<String> scanJarFileForClasses(File file) throws IOException, IllegalArgumentException
{
if (file == null || !file.exists())
throw new IllegalArgumentException("Invalid jar-file to scan provided");
if (file.getName().endsWith(".jar"))
{
List<String> foundClasses = new ArrayList<String>();
try (JarFile jarFile = new JarFile(file))
{
Enumeration<JarEntry> entries = jarFile.entries();
while (entries.hasMoreElements())
{
JarEntry entry = entries.nextElement();
if (entry.getName().endsWith(".class"))
{
String name = entry.getName();
name = name.substring(0,name.lastIndexOf(".class"));
if (name.indexOf("/")!= -1)
name = name.replaceAll("/", ".");
if (name.indexOf("\\")!= -1)
name = name.replaceAll("\\", ".");
foundClasses.add(name);
}
}
}
return foundClasses;
}
throw new IllegalArgumentException("No jar-file provided");
}
一旦知道 jar 文件中包含的类,您需要加载每个类并检查它们是否实现了所需的接口,如下所示:
/**
* <p>
* Looks inside a jar file and looks for implementing classes of the provided interface.
* </p>
*
* @param file
* The Jar-File containing the classes to scan for implementation of the given interface
* @param iface
* The interface classes have to implement
* @param loader
* The class loader the implementing classes got loaded with
* @return A {@link List} of implementing classes for the provided interface
* inside jar files of the <em>ClassFinder</em>s class path
*
* @throws Exception If during processing of the Jar-file an error occurred
*/
public List<Class<?>> findImplementingClassesInJarFile(File file, Class<?> iface, ClassLoader loader) throws Exception
{
List<Class<?>> implementingClasses = new ArrayList<Class<?>>();
// scan the jar file for all included classes
for (String classFile : scanJarFileForClasses(file))
{
Class<?> clazz;
try
{
// now try to load the class
if (loader == null)
clazz = Class.forName(classFile);
else
clazz = Class.forName(classFile, true, loader);
// and check if the class implements the provided interface
if (iface.isAssignableFrom(clazz) && !clazz.equals(iface))
implementingClasses.add(clazz);
}
catch (ClassNotFoundException e)
{
e.printStackTrace();
}
}
return implementingClasses;
}
因为您现在可以收集某个接口的所有实现,您可以通过以下方式简单地初始化一个新实例
public void executeImplementationsOfAInJarFile(File downloadedJarFile)
{
If (downloadedJarFile == null || !downloadedJarFile.exists())
throw new IllegalArgumentException("Invalid jar file provided");
URL downloadURL = downloadedJarFile.toURI().toURL();
URL[] downloadURLs = new URL[] { downloadURL };
URLClassLoader loader = URLClassLoader.newInstance(downloadURLs, getClass().getClassLoader());
try
{
List<Class<?>> implementingClasses = findImplementingClassesInJarFile(downloadedJarFile, A.class, loader);
for (Class<?> clazz : implementingClasses)
{
// assume there is a public default constructor available
A instance = clazz.newInstance();
// ... do whatever you like here
}
}
catch (Exception e)
{
e.printStackTrace();
}
}
请注意,此示例假定 A 是一个接口。如果在 Jar 文件中找不到实现类,则 jar 文件将由类加载器加载,但不会发生对象的实例化。
进一步注意,提供父类加载器始终是一种好习惯——尤其是使用 URLClassLoader。否则,Jar-File 中不包含的某些类可能会丢失,因此您可能会ClassNotFoundException
尝试访问它们。这是由于类加载器使用的委托机制,它首先询问其父级是否知道所需类的类定义。如果是这样,则该类将由父类加载;如果不是,则该类将由创建的 URLClassLoader 加载。
请记住,使用不同的 ClassLoader 多次加载同一个类是可能的(peer-classloaders)。但是,尽管类的名称和字节可能相同,但由于使用了不同的类加载器实例,类不兼容 - 因此尝试将类加载器 A 加载的实例转换为类加载器 B 加载的类型将失败。
@Edit:修改代码以避免返回空值,而是抛出或多或少适当的异常。@Edit2:由于我无法接受代码审查建议,我将审查直接编辑到帖子中