从单独的jar调用.asSubclass时抛出ClassCastException

时间:2016-06-27 02:01:41

标签: java reflection jar runtime-error dynamic-cast

我有一个程序,通过它我有以下三个类。前两个位于jar1.jar

Main(使用找到的jar加载技巧here):

package prob1;

import java.io.IOException;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;

public class Main {
    static List<Class<?>> classes = new ArrayList<Class<?>>();

    static String pathToJar = "/Users/vtcakavsmoace/Desktop/jar2.jar";

    public static void main(String[] args) throws ClassNotFoundException, IOException, InstantiationException, IllegalAccessException {
        loadJar();

        classes.get(0).asSubclass(A.class).newInstance().someMethod();
    }

    private static void loadJar() throws IOException, ClassNotFoundException {
        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;
            }

            String className = je.getName().substring(0, je.getName().length() - 6);
            className = className.replace('/', '.');
            classes.add(cl.loadClass(className));
        }

        jarFile.close();
    }
}

A

package prob1;

public interface A {
    void someMethod();
}

jar2.jarB中找到第二个课程:

package prob2;

import prob1.A;

public class B implements A {

    @Override
    public void someMethod() {
        System.out.println("Hello, world!");
    }

}

如您所见,类B显然实现了接口A。但是,在加载类B,然后尝试在其上调用asSubclass时,会失败并出现以下异常:

Exception in thread "main" java.lang.reflect.InvocationTargetException
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:497)
    at org.eclipse.jdt.internal.jarinjarloader.JarRsrcLoader.main(JarRsrcLoader.java:58)
Caused by: java.lang.ClassCastException: class prob2.B
    at java.lang.Class.asSubclass(Class.java:3404)
    at prob1.Main.main(Main.java:20)
    ... 5 more

请注意,在Eclipse中运行时不会失败。

我在这里做错了什么?我该如何解决这个问题?

1 个答案:

答案 0 :(得分:0)

好的,根据Erwin Bolwidt给我的知识找到答案;在课程Main中,替换:

URLClassLoader cl = URLClassLoader.newInstance(urls);

使用:

URLClassLoader cl = URLClassLoader.newInstance(urls, Main.class.getClassLoader());

解决了这个问题。 :P