Java 最佳实践:将子类对象放入需要超类对象的 HashMap 中
假设我用 SuperClass
作为值类型实例化一个 HashMap。然后,我将 SubClass
对象作为值添加到 Map。当我从 Map 检索这些值时,它们作为 SuperClass
类型的对象返回,我将其显式转换回 Subclass
:
class SuperClass {}
class SubClass1 extends SuperClass { int one;}
class SubClass2 extends SuperClass { int two;}
class DoSomething {
DoSomething() {
Map<String, SuperClass> map = new HashMap<String, SuperClass>();
map.put("1", new SubClass1());
map.put("2", new SubClass2());
SubClass1 one = (SubClass1) map.get("1");
}
}
我需要知道返回的对象是特定的子类,因为我想访问仅存在于子类中的方法。如果返回的类型可以是任意数量的不同子类,那么使用 instanceof
是否被认为是确定类型和转换的最佳实践?
SuperClass s = map.get("1");
if (s instanceof SubClass1) {
(SubClass1)s.one = 1;
}
谢谢
Let's say I instantiate a HashMap with SuperClass
as value-type. I then add SubClass
objects as values to the Map. When I retrieve those values from the Map, they are returned as objects of type SuperClass
, which I explicitly cast back to Subclass
:
class SuperClass {}
class SubClass1 extends SuperClass { int one;}
class SubClass2 extends SuperClass { int two;}
class DoSomething {
DoSomething() {
Map<String, SuperClass> map = new HashMap<String, SuperClass>();
map.put("1", new SubClass1());
map.put("2", new SubClass2());
SubClass1 one = (SubClass1) map.get("1");
}
}
I need to know that the returned object is of the specific SubClass
because I want to access methods that only exist in the SubClass. If the returned type can be any number of different SubClasses, is the use of instanceof
considered best practice in determining the type and the casting?
SuperClass s = map.get("1");
if (s instanceof SubClass1) {
(SubClass1)s.one = 1;
}
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
最佳实践应该是将每个子类类型放入不同的映射中。
在执行强制转换之前使用instanceof,如果您确实需要执行该强制转换,这是一个好主意,因为这样您将防止出现ClassCastException。
请注意,如果您的代码有很多 instanceof 指令,那么您的设计可能会很糟糕。
如果您想将它们放在同一个 Map 中,那么您需要考虑您的设计:
让您的 DoSomething 类了解不同的 SubClass 类型以执行特定操作?我看到 3 种可能性:
The best practice should be putting each SubClass type inside a different Map.
Using instanceof before performing a cast, if you really need to do that cast, it's a good idea because this way you will prevent a ClassCastException.
Pay attention that if your code has a lot of instanceof directives then you could have a bad design.
If you want to put them in the same Map then you need to think about your design:
have your DoSomething class to be aware of the differents SubClass types to perform specific operation?I see 3 possibilities:
是的,你绝对应该使用instanceof来保证类型安全。否则,您如何知道您提取的对象实际上是否是正确的子类?
Yes, you should definitely use instanceof to be typesafe. Otherwise, how would you know whether or not the object you pulled out is in fact the correct subclass?
根据具体情况,有多种方法:
There are a number of ways about this depending upon the particular situation: