【发布时间】:2023-04-10 22:40:01
【问题描述】:
随着泛型的引入,我不愿意尽可能多地执行 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 检查,如果有其他方法可以做到这一点,我会很感兴趣。
谢谢
【问题讨论】:
-
有没有办法利用多态性?比如,在
MyObject和OtherObject中都有一个doFurtherProcessing()方法做正确的事? -
我怀疑首先需要这样做是问题所在。为什么这些物体首先会混在一起?