Java 从另一个具有依赖项的 Jar 创建类实例



我正在尝试从另一个jar创建一个类的实例,问题是所有的类都与我拥有的类不同,所以如果我尝试调用一个需要Test的方法.class,我得到一个非法参数异常

我尝试从路径中创建一个 JarFile,检查以确保它是一个类(我检查 jar 中的每个类(,使用 jar 路径和我的 jar 路径创建一个 URLClassLoader,使用 URLClassLoader 加载类,检查以确保它具有正确的超类,然后将其存储在列表中以供以后使用。

现在我不能对子类做任何事情,我不能把它强制转换为超类,因为它是通过另一个加载器加载的。

if(folder.listFiles() == null) return;
for(File files : folder.listFiles()) {
if(files.getName().endsWith(".jar")) {
try {
JarFile jarFile = new JarFile(files.getAbsolutePath());
Enumeration<JarEntry> enumerator = jarFile.entries();
URL[] urls = {new URL("jar:file:" + files.getAbsolutePath() + "!/"), new URL("jar:file:" + CurrentClass.class.getProtectionDomain().getCodeSource().getLocation()
.toURI().getPath() + "!/")};
URLClassLoader cl = URLClassLoader.newInstance(urls);
while (enumerator.hasMoreElements()) {
JarEntry file = enumerator.nextElement();
if (file.isDirectory() || !file.getName().endsWith(".class")) {
continue;
}
String className = file.getName().substring(0, file.getName().length() - 6);
className = className.replace('/', '.');
Class clazz = cl.loadClass(className);
if(clazz.getSuperclass().getName().equals(MyClass.class.getName())) {
found.add(clazz);
}
}
} catch (Exception e) {
logger.severe("Could not load jar at path: " + enchants.getPath());
logger.log(Level.SEVERE, e, () -> "Error:");
}
}
}

返回的类不是同一类的子类,所以我不能用它做太多事情。我将如何使用正确的超类加载它?或者我怎么能把它投到超阶级?

经过更多的试验,我试图避免做任何选角,但不能完全避免。如果有某种方法可以通用地转换或其他东西,那会很好,我只需要将其保存到一个列表中,其中包含从其他 jar 加载的其他类。

由于不清楚,这里有一个更好的解释

Jar A 需要从 jar B 创建一个类的实例。jar B 中的类必须是 jar A 中类的子类,因为我将它们添加到列表中,并且无法将其添加为依赖项。

很抱歉含糊不清,我想我必须将原始类加载器传递给子类加载器,以便为其提供原始超类的正确类实例。

最新更新