简体   繁体   English

相同泛型类型的泛型数组的泛型类

[英]Generic class to array of generics of same generic type

I have a method signature like 我有一个方法签名就像

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

But I'm not sure how I can create that T[] type from Class<T> . 但我不确定如何从Class<T>创建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 (ie T[] ) already, which is of no use and redundant. 我已经尝试过使用Collection<T>但是我无法Array.newInstance(Class<?>, int) (T[]) collection.toArray()Array.newInstance(Class<?>, int)请求一个数组类(即T[] ),其中是没有用的,多余的。

Also, obvisously, new T[n] does not work. 另外,很明显, new T[n]不起作用。

I would presume it's something easy, but I'm numb for the solution right now :) 我认为这很容易,但我现在麻木了解决方案:)

Thanks. 谢谢。

newInstance does not ask for an array class, it asks for the component type. newInstance不要求数组类,它要求组件类型。 It will work fine, albeit with the usual problems with unchecked casts and generic arrays. 尽管未经检查的强制转换和通用数组存在常见问题,但它仍然可以正常工作。

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

But why mix arrays and Generics at all? 但是为什么要混合数组和泛型呢? It'll just lead to headaches. 这只会导致头痛。 Use something from the Collections API, like List . 使用Collections API中的内容,例如List

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM