编辑:解决,见下文
嗨,
在Java中,我得到了一个可以属于任何类的对象.但是 - 该对象将始终必须实现接口,因此当我调用接口定义的方法时,该对象将包含该方法.
现在,当您尝试在Java中的通用对象上调用自定义方法时,它会轻松打字.我怎么能以某种方式告诉编译器我的对象确实实现了该接口,因此调用该方法是可以的.
基本上,我正在寻找的是这样的:
Object(MyInterface) obj; // Now the compiler knows that obj implements the interface "MyInterface"
obj.resolve(); // resolve() is defined in the interface "MyInterface"
Run Code Online (Sandbox Code Playgroud)
我怎么能用Java做到这一点?
解答:好的,如果界面名为MyInterface,你可以放
MyInterface obj;
obj.resolve();
Run Code Online (Sandbox Code Playgroud)
很抱歉在发布前不思考....
if (object instanceof MyInterface) {
((MyInterface) object).resolve();
}
Run Code Online (Sandbox Code Playgroud)