First I know this is quite dirty job, and if there is a way, it may be consider "bad practice". Unfortunately, I have to explore the possibility.
I would like to know if I can cast an object that in practice implements a Interface but in fact do not. I mean, the class implements all the methods but do not have the "implement interface" in the declaration. Additionally, I would prefer to do this and finally get the Object typed. Example below
interface IA{
void method();
}
class CB{
void method(){;}
}
public class foo{
public static void main(String[] args){
/*magic to cast the object without exception*/
IA ob= (IA) new CB();
ob.method();
}
}
I want to get this IA object at the end.
Consider a much safer alternative.
Wrap the object you want to cast, into a class that implements the interface and delegate the method calls to the wrapped object.
Example:
public class CBWrapper implements IA {
CB target;
public CBWrapper(CB target) {
this.target = target;
}
@Override
void method() {
target.method();
}
}
You cannot cast an Object to interface it doesn't implements.
You can access object's method using reflection and call a specific method by name or whatever.
However, I think you should ask yourself what you want to do and is there a simpler way to do it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With