Java添加到未知类型的通用列表 [英] Java adding to a unknown type generic list

查看:140
本文介绍了Java添加到未知类型的通用列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我之前遇到过一些我以前没有遇到过的东西,也就是说,我需要在运行时创建一个新的ArrayList类实例而不分配已知类型然后将数据添加到列表中。这听起来有点模糊,所以这是一个例子:

I've come into something I haven't come across before in Java and that is, I need to create a new instance of say the ArrayList class at runtime without assigning a known type then add data to the list. It sounds a bit vague so here is an example:

Class<?> c = i.getClass();

Constructor<?> con = ArrayList.class.getConstructor();
ArrayList<?> al = (ArrayList<?>)con.newInstance();

al.add("something");

现在我这样做的原因与仅仅使用泛型是因为泛型已被大量使用这个例子中的i变量将被用作?类型。我真的不想抛弃另一个泛型,因为这会给用户带来更多的工作,并且在最终设计中灵活性会低得多。有没有办法使用下面的东西(注意:下面的内容不起作用)。有人有想法吗?

Now the reason I'm doing this versus just using generics is because generics are already being used heavily and the "i" variable in this example would be given to use as type "?". I would really rather not throw in another generic as this would cause more work for the user and would be much less flexible in the end design. Is there any way to use something like below (Note: what is below doesn't work). Anyone have ideas?

ArrayList<c> al = (ArrayList<c>)con.newInstance();


推荐答案

您无法在使用定义的集合中添加对象通配符泛型。 此主题可能会对您有所帮助。

You can't add objects in a Collection defined using wildcards generics. This thread might help you.

确实,您正在创建一个集合,是的,每个集合的超类型,因此,可以分配给任何泛型集合;但是它太通用了,不允许任何类型的添加操作,因为编译器无法检查你要添加的内容的类型。而这正是泛型的意思:类型检查。

Indeed you are creating a collection that is, yes, the super type of every collection, and as such, can be assigned to any collection of generics; but it's too generic to allow any kind of add operation as there is no way the compiler can check the type of what you're adding. And that's exactly what generics are meant to : type checking.

我建议你阅读这个帖子,看看它也适用于你想做的事情。

I suggest you read the thread and see that it also apply to what you wanna do.

您的集合太通用了,无法添加任何内容。问题与asignment的右侧无关(使用单例或反射) ,它位于使用通配符的左侧声明类型中。

Your collection is just too generic to allow anything to be added in. The problem has nothing to do with the right hand side of the asignment (using a singleton or reflection), it's in the left hand side declaration type using wildcards.

这篇关于Java添加到未知类型的通用列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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