不知道具体类型的实例化对象 [英] Instantiating object without knowing the concrete type

查看:136
本文介绍了不知道具体类型的实例化对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在创建以下java类。

 类EntityCollection< E扩展实体,M扩展Hashmap<?,E> {
}

这个想法是这个类的用户会告诉我什么类型的对象保存在收藏和实际存储中。所以M可以是简单的Hashmap或LinkedHashmap。



我有两个问题:
我将如何在我的课程中实例化M?这是可能吗?



AND



这是一个很好的方法,还是应该采取一些StoreFactory会让我回来商店使用?我应该在这个类的构造函数中使用吗?

解决方案

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



给予这个阅读:



在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?

这篇关于不知道具体类型的实例化对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆