泛型类相同的通用类型的泛型数组 [英] Generic class to array of generics of same generic type

查看:140
本文介绍了泛型类相同的通用类型的泛型数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个像

public <T extends SomeClass> T[] findAll(Class<T> oClass, String condition)

但我不知道我怎么可以创建一个 T [] 类和LT型; T&GT; 。我尝试用收藏&LT; T&GT; 但我不能投(T [])collection.toArray() Array.newInstance(类&LT;&gt;中INT)要求数组类(即 T [] )已经,这是没有用的和冗余。

But I'm not sure how I can create that T[] type from Class<T>. I've tried using a Collection<T> but I cannot cast (T[]) collection.toArray() and Array.newInstance(Class<?>, int) asks for an array class (i.e. T[]) already, which is of no use and redundant.

此外,obvisously,新T [N] 不起作用。

Also, obvisously, new T[n] does not work.

我想presume它的东西很容易,但我现在很麻木的解决办法:)

I would presume it's something easy, but I'm numb for the solution right now :)

感谢。

推荐答案

的newInstance 不要求数组类,它要求组件类型。它会正常工作,尽管与选中的演员和通用阵列的常见问题。

newInstance does not ask for an array class, it asks for the component type. It will work fine, albeit with the usual problems with unchecked casts and generic arrays.

T[]  myArr = (T[]) Array.newInstance(oClass, length);

但为什么混合阵列和泛型呢?这将只是导致头痛。使用从集合API,像列表

这篇关于泛型类相同的通用类型的泛型数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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