![](/img/trans.png)
[英]ClassCastException when casting Class.forName object to interface implemented by this object
[英]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.