Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cast object to interface did not implement?

Tags:

java

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.

like image 650
ender.an27 Avatar asked Dec 20 '25 16:12

ender.an27


2 Answers

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();
    }
}
like image 189
kupsef Avatar answered Dec 22 '25 06:12

kupsef


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.

like image 29
BobTheBuilder Avatar answered Dec 22 '25 07:12

BobTheBuilder



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!