Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
280 views
in Technique[技术] by (71.8m points)

java - can't cast to implemented interface

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;

I get a ClassCastException!

ClassCastException: Device cannot be cast to AutocompleteResult

Also, isAssignableFrom returns false and i'm not sure why:

log.debug(AutocompleteResult.class.isAssignableFrom(Device.class));

from the doc:

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?

Thanks.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...