随着泛型的引入,我不愿意尽可能地执行instanceof或强制转换。但在这种情况下我没有看到解决方法:
for (CacheableObject<ICacheable> cacheableObject : cacheableObjects) {
ICacheable iCacheable = cacheableObject.getObject();
if (iCacheable instanceof MyObject) {
MyObject myObject = (MyObject) iCacheable;
myObjects.put(myObject.getKey(), myObject);
} else if (iCacheable instanceof OtherObject) {
OtherObject otherObject = (OtherObject) iCacheable;
otherObjects.put(otherObject.getKey(), otherObject);
}
}
在上面的代码中,我知道我的 ICacheables 应该只是 MyObject 或 OtherObject 的实例,并且根据这一点,我想将它们放入 2 个单独的映射中,然后进一步执行一些处理。
我很感兴趣是否有另一种方法可以在没有我的instanceof检查的情况下做到这一点。
Thanks
您可以使用双重调用。不承诺这是一个更好的解决方案,但它是一个替代方案。
代码示例
import java.util.HashMap;
public class Example {
public static void main(String[] argv) {
Example ex = new Example();
ICacheable[] cacheableObjects = new ICacheable[]{new MyObject(), new OtherObject()};
for (ICacheable iCacheable : cacheableObjects) {
// depending on whether the object is a MyObject or an OtherObject,
// the .put(Example) method will double dispatch to either
// the put(MyObject) or put(OtherObject) method, below
iCacheable.put(ex);
}
System.out.println("myObjects: "+ex.myObjects.size());
System.out.println("otherObjects: "+ex.otherObjects.size());
}
private HashMap<String, MyObject> myObjects = new HashMap<String, MyObject>();
private HashMap<String, OtherObject> otherObjects = new HashMap<String, OtherObject>();
public Example() {
}
public void put(MyObject myObject) {
myObjects.put(myObject.getKey(), myObject);
}
public void put(OtherObject otherObject) {
otherObjects.put(otherObject.getKey(), otherObject);
}
}
interface ICacheable {
public String getKey();
public void put(Example ex);
}
class MyObject implements ICacheable {
public String getKey() {
return "MyObject"+this.hashCode();
}
public void put(Example ex) {
ex.put(this);
}
}
class OtherObject implements ICacheable {
public String getKey() {
return "OtherObject"+this.hashCode();
}
public void put(Example ex) {
ex.put(this);
}
}
这里的想法是 - 而不是铸造或使用instanceof
- 你打电话给iCacheable
对象的.put(...)
方法将自身传递回Example
对象的重载方法。调用哪个方法取决于该对象的类型。
另请参阅访客模式。我的代码示例有味道,因为ICacheable.put(...)
方法是不内聚的 - 但使用访问者模式中定义的接口可以清除这种气味。
为什么我不能直接打电话this.put(iCacheable)
来自Example
class?
在Java中,重写总是在运行时绑定的,但重载稍微复杂一些:动态分派意味着方法的实现将在运行时选择,但方法的签名仍然在编译时确定。 (查看Java 语言规范,第 8.4.9 章欲了解更多信息,还可以查看本书第 137 页的益智游戏“Making a Hash of It”Java 谜题.)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)