Reputation: 897
Let say I have a class:
class A{
void doSomething();
}
And also, I have an interface:
interface I{
void doSomething();
}
Is it possible to cast object A
as I
?
A object = new A();
I objectInterface = (I) object;
I get an error java.lang.ClassCastException: A cannot be cast to I
. Why does this occur and can I create a partial interface for an object that does not implement that interface? I do not have control of that class.
Upvotes: 1
Views: 670
Reputation: 140457
It happens because that is how Java works.
Java doesn't allow what other languages call "duck typing".
Meaning: a class X implementing all methods that belong to an interface Y is not sufficient for someX instanceof Y
to return true
.
Only when the class definition says class X implements Y
that instanceof / cast are valid. When you can't change the class definition, then a cast is not possible.
One solution for you would be to look into reflection and dynamic proxies.
Meaning: when you have an interface Y, and you would know how to delegate invocations of interface methods (for example to methods of a an object of class X), then you can do that dynamically, using that proxy concept.
Disclaimer: as in everything that is based on reflection, such code is easy to get wrong, and hard to maintain over time. So follow that tutorial step by step, do a lot of research and ensure you really understand what you are doing! But it does work, and many interesting features of large frameworks such as spring make use of dynamic proxies.
Upvotes: 1
Reputation: 308813
If you don't have control over class A
, and you have to be able to use it as a polymorphic interface I
at runtime, then you'll have to wrap it:
public class B implements I {
private A a;
public B(a) { this.a = a; }
public void doSomething() { this.a.doSomething(); }
}
Upvotes: 2