Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java - Make sure an object implements an interface

Tags:

java

interface

EDIT: Solved, see below

Hi,

In Java, I got an object that could be of any class. BUT - that object will always have to implement an interface, so when I call methods defined by the interface, that object will contain that method.

Now, when you try to call a custom method on a generic object in Java, it mucks about typing. How can I somehow tell the compiler that my object does implement that interface, so calling the method is OK.

Basically, what I'm looking for is something like this:

Object(MyInterface) obj; // Now the compiler knows that obj implements the interface "MyInterface"
obj.resolve(); // resolve() is defined in the interface "MyInterface"

How can I do that in Java?

ANSWER: OK, if the interface is named MyInterface you can just put

MyInterface obj;
obj.resolve();

Sorry for not thinking before posting ....

like image 781
Jake Avatar asked Jan 16 '10 14:01

Jake


3 Answers

You just do it with a type cast:

((MyInterface) object).resolve();

Usually it is best to do a check to make sure that this cast is valid -- otherwise, you'll get a ClassCastException. You can't shoehorn anything that doesn't implement MyInterface into a MyInterface object. The way you do this check is with the instanceof operator:

if (object instanceof MyInterface) {
    // cast it!
}
else {
    // don't cast it!
}
like image 104
Kaleb Brasee Avatar answered Nov 16 '22 17:11

Kaleb Brasee


if (object instanceof MyInterface) {
    ((MyInterface) object).resolve();
}
like image 31
Bozho Avatar answered Nov 16 '22 17:11

Bozho


MyInterface a = (MyInterface) obj;
a.resolve();

or

((MyInterface)obj).resolve();

the java compiler uses the static type to check for methods, so you have to either cast the object to a type which implements your interface or cast to the interface itself.

like image 1
josefx Avatar answered Nov 16 '22 17:11

josefx