因为类加载器的ClassCastException异常?(ClassCastException be

2019-06-26 21:10发布

虽然与类加载器打我得到了以下异常:

Exception in thread "main" java.lang.ClassCastException: xxx.Singleton cannot be cast to xxx.Singleton

这是否意味着从一个类加载器的实例不是强制转换为一个类加载器的另一个吗?

检查我的代码在那里我能3单身感谢实例化到类加载器,甚至与“”安全。

public static void main(String[] args) throws Exception {
        URL basePath = new URL("file:/myMavenPath/target/classes/");

    Object instance = getClassInstance(Singleton.class);
    System.out.println(instance);
    //
    Object instance2 = getClassInstance(
            new URLClassLoader( new URL[]{basePath} , null )
                    .loadClass("my.Singleton")
    );
    System.out.println(instance2);
    //
    Object instance3 = getClassInstance(
            new URLClassLoader( new URL[]{basePath} , null )
                    .loadClass("my.Singleton")
    );
    System.out.println(instance3);

    // Only the 1st cast is ok
    Singleton testCast1 = (Singleton) instance;
    System.out.println("1st cast ok");
    Singleton testCast2 = (Singleton) instance2;
    System.out.println("2nd cast ok");
    Singleton testCast3 = (Singleton) instance3;
    System.out.println("3rd cast ok");
}

private static Object getClassInstance(Class clazz) throws Exception {
    Method method = clazz.getMethod("getInstance");
    method.setAccessible(true);
    return method.invoke(null);
}


class Singleton {

    private static final Singleton INSTANCE = new Singleton();

    public static Singleton getInstance() {
        return INSTANCE;
    }

    private Singleton() {
        Exception e = new Exception();
        StackTraceElement[] stackTrace = e.getStackTrace();
        if (!"<clinit>".equals(stackTrace[1].getMethodName())) {
            throw new IllegalStateException("You shall not instanciate the Singleton twice !",e);
        }
    }

    public void sayHello() {
        System.out.println("Hello World ! " + this);
    }

}

Answer 1:

你不能类加载器之间进行转换。 阶级身份是由完全合格的名称和类加载器。 检查阶级身份孤岛 这里 。



Answer 2:

这也正是如此。 不能使用不同的类加载器加载的类之间铸造。

这个问题,“铸跨类加载器”可以让事情更清晰......



Answer 3:

是的,你是对的。

这种情况经常发生在OSGi的项目,因为不好的依赖管理。



文章来源: ClassCastException because of classloaders?