随着泛型的引入,我尽可能地不想执行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()
方法,可以做正确的事情吗? - NullUserException