gpt4 book ai didi

java - 这里的 instanceof 检查有什么问题吗?

转载 作者:搜寻专家 更新时间:2023-11-01 03:09:47 25 4
gpt4 key购买 nike

随着泛型的引入,我舍不得尽可能的进行instanceof或者casting。但在这种情况下我看不到解决方法:

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 检查,是否还有另一种方法可以做到这一点,我很感兴趣。

谢谢

最佳答案

您可以使用双重调用。不能保证它是更好的解决方案,但它是一种替代方案。

代码示例

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);
}

}

这里的想法是 - 您调用 iCacheable 对象的 .put(...) 方法而不是强制转换或使用 instanceof它将自身传递回 Example 对象的重载方法。调用哪个方法取决于该对象的类型。

另见 Visitor pattern .我的代码示例有异味,因为 ICacheable.put(...) 方法没有内聚性 - 但使用访问者模式中定义的接口(interface)可以消除这种异味。

为什么我不能从 Example 类中调用 this.put(iCacheable)

在 Java 中,覆盖总是在运行时绑定(bind),但重载稍微复杂一些:动态调度意味着方法的实现将在运行时选择,但方法的签名仍然在编译时确定。 (查看 Java Language Specification, Chapter 8.4.9 了解更多信息,还可以查看 Java Puzzlers 一书第 137 页的益智游戏“Making a Hash of It”。)

关于java - 这里的 instanceof 检查有什么问题吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13204215/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com