簡體   English   中英

實例化一個類並將其強制轉換為該類正在實現的接口時,為什么會出現ClassCastException?

[英]Why am I getting ClassCastException when I instantiate a class and casting it to that interface which is being implemented by this class?

我是這個ClassLoader概念的新手。 我為此花了將近一個星期的時間,但找不到任何解決方案。

URLClassLoader jarLoader = new URLClassLoader (urlList);
Class clazz = jarLoader.loadClass(classname);
Object instance=clazz.newInstance();
(Interface1)(instance);

在這里,在第4行中,我得到了ClassCastException

請幫我解決這個問題? 我將不勝感激。

聽起來Interface1由兩個不同的類加載器加載。 您正在將其強制轉換為Interface1 (A),但您的jarLoader希望它為Interface1 (B)。

您確定urlList不包含以前加載的類的URL嗎? 還是Interface1的其他版本?

這將幫助您找到錯誤(使用此錯誤代替(Interface1)(instance); ):

Class<?>[] interfaces = instance.getClass().getInterfaces();
for (Class<?> interfaceType : interfaces) {
    System.out.println("---------");
    System.out.println(interfaceType);
    System.out.println(interfaceType.getClassLoader());
    System.out.println(
        interfaceType.getProtectionDomain().getCodeSource().getLocation());
}

這可能是因為Interface1已由其他類加載器加載。

然后使用以另一個classLoader作為參數的構造函數-傳遞與接口關聯的類加載器。

URLClassLoader = new URLClassLoader(urlList,Interface1.class.getClassLoader())

您遇到的問題是,該類正在實現URLClassLoader加載的接口,在您嘗試將其強制轉換為其他類加載器加載的接口時。

Interface1可能是由與您的類不同的類加載器加載的。 當由不同的類加載器加載時,類被認為是不同的。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM