无法强制转换为已实现的界面 [英] can't cast to implemented interface

查看:127
本文介绍了无法强制转换为已实现的界面的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我很困惑......

i'm very confused...

我有一个直接实现接口的类:

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));

。 2 / docs / api / java / lang / Class.html#isAssignableFrom%28java.lang.Class%29> doc :

from the 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).

这是一个常见原因,如果你使用一些k ind of plugin系统以及你的基类和插件类提供相同的类。

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() 两个违规类(即由设备 实现的接口类, 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆