且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

不知道具体类型的实例化对象

更新时间:2023-02-14 11:53:36

你不能这样做,键入擦除。你可以让他们通过班级给你。



给予这个阅读:



在Java中创建通用类型的实例


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?