不知道具体类型的实例化对象 [英] Instantiating object without knowing the concrete type
问题描述
类EntityCollection< E扩展实体,M扩展Hashmap<?,E> {
}
这个想法是这个类的用户会告诉我什么类型的对象保存在收藏和实际存储中。所以M可以是简单的Hashmap或LinkedHashmap。
我有两个问题:
我将如何在我的课程中实例化M?这是可能吗?
AND
这是一个很好的方法,还是应该采取一些StoreFactory会让我回来商店使用?我应该在这个类的构造函数中使用吗?
你不能这样做,键入擦除。你可以让他们通过班级给你。
给予这个阅读:
I am creating following java class.
class EntityCollection <E extends Entity, M extends Hashmap<?,E>> {
}
The idea is that the user of this class will tell me what type of objects to save in the collection and the actual store. So M can be simple Hashmap or LinkedHashmap.
I have two questions here: How would I instantiate M inside my class? Is it possible?
AND
Is this a good approach or should I take some StoreFactory that would return me the store to use? Should I take that in the constructor of this class?
You can't do this the way you're set up due to type erasure. You can pull it off by having them pass the class to you.
Give this a read:
Create instance of generic type in Java?
这篇关于不知道具体类型的实例化对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!