开发者

Java - Make sure an object implements an 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 interf开发者_如何学JAVAace "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 ....


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!
}


if (object instanceof MyInterface) {
    ((MyInterface) object).resolve();
}


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜