无法转换为已实现的接口 [英] can't cast to implemented interface
问题描述
我很困惑...
我有一个直接实现接口的类:
I have a class which directly implements an interface:
public class Device implements AutocompleteResult
{...}
以下证明我正在查看正确的变量:
Here is proof that I'm looking at the right variables:
Object match = ...;
log.debug(match.getClass()); // Outputs 'Device'
log.debug(match.getClass().getInterfaces()[0]); // Outputs 'AutocompleteResult'
然而,当我尝试将类的实例转换为接口时:
Yet when I try to cast an instance of the class to the interface:
AutocompleteResult result = (AutocompleteResult) match;
我收到一个 ClassCastException!
I get a ClassCastException!
ClassCastException: Device cannot be cast to AutocompleteResult
此外,isAssignableFrom
返回 false,我不知道为什么:
Also, isAssignableFrom
returns false and i'm not sure why:
log.debug(AutocompleteResult.class.isAssignableFrom(Device.class));
来自 doc:
确定此 Class 对象表示的类或接口是否与所表示的类或接口相同,或者是其超类或超接口通过指定的 Class 参数.
Determines if the class or interface represented by this Class object is either the same as, or is a superclass or superinterface of, the class or interface represented by the specified Class parameter.
我不应该总是能够将一个对象转换为它的类实现的接口吗?
Shouldn't I always be able to cast a object to an interface its class implements?
谢谢.
推荐答案
如果两个不同的类加载器加载名为 AutocompleteResult
的类,就会发生这种情况.
This can happen if two different classloaders load a class named AutocompleteResult
.
这两个类被视为完全不同的类,即使它们具有相同的包和名称(甚至实现/字段/方法).
These two classes are then treated as entirely different classes, even if they have the same package and name (and even implementation/fields/methods).
造成这种情况的一个常见原因是,如果您使用某种插件系统并且您的基类和插件类提供相同的类.
A common cause for this is if you use some kind of plugin system and both your base classes and the plugin classes provide the same class.
要检查此问题,请打印 Class.getClassLoader()
在两个违规类(即由Device
实现的接口的类和<代码>AutocompleteResult.class).
To check for this issue print the value returned by Class.getClassLoader()
on both offending classes (i.e. the class of the interface implemented by Device
and the result of AutocompleteResult.class
).
这篇关于无法转换为已实现的接口的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!