[英]Java passing Array to generic method
I have this generic method: 我有这种通用方法:
public <T> T get(Class<T> type, String... keys)
{
String key = String.join(".", keys);
if(this._data.containsKey(key))
return type.cast(this._data.get(key));
return null;
}
and I need to pass a generic Array as type but I don't understand how to do it: 而且我需要将通用数组作为类型传递,但我不知道该怎么做:
public <T extends SearchableItem> ArrayList<T> filterAudio(T[] type, int taxonomyId, TaxonomyLevel level, int count) {
T[] all = (T[])masterDbManager.get(type, "audiotracks-alphabetic");
....
}
But that doesn't work because the get() method wants a class: 但这不起作用,因为get()方法需要一个类:
Error:(200, 39) java: method get in class com.xxxxxx.yyyyy.dal.MasterDbManager cannot be applied to given types; 错误:(200,39)java:com.xxxxxx.yyyyy.dal.MasterDbManager类中的方法无法应用于给定类型; required: java.lang.Class,java.lang.String[] found: T[],java.lang.String reason: cannot infer type-variable(s) T (argument mismatch; T[] cannot be converted to java.lang.Class) 必需:java.lang.Class,java.lang.String []找到:T [],java.lang.String原因:无法推断类型变量T(参数不匹配; T []无法转换为Java。 lang.Class)
not an Array, so how can I use the get() method when I need to retrieve an Array? 不是数组,那么当我需要检索数组时如何使用get()方法?
Hope my request is clear :) 希望我的要求清楚:)
EDIT : ok I needed the .getClass() method 编辑 :好的,我需要.getClass()方法
T[] all = (T[])masterDbManager.get(type.getClass(), dbKey);
BUT how do I now call the filterAudio() method from the following method? 但是如何现在从以下方法调用filterAudio()方法?
public <T> ArrayList<T> searchAudio(Class<T> type, int taxonomyId, TaxonomyLevel taxonomyLevel, String searchText, int page, int pageSize, SearchOrder order) {
ArrayList<T> all = filterAudio(???, taxonomyId, taxonomyLevel, 0);
...
}
In your specific case you can simply write (T[])masterDbManager.get(Object.class, "audiotracks-alphabetic")
because you cast result to T[]
anyway. 在您的特定情况下,您可以简单地编写(T[])masterDbManager.get(Object.class, "audiotracks-alphabetic")
因为无论如何都将结果(T[])masterDbManager.get(Object.class, "audiotracks-alphabetic")
为T[]
。
In general there is no Class
corresponding to T[]
type. 通常,没有对应于T[]
类型的Class
。 It will by always Array.class
no matter what base type array have. 无论具有哪种基本类型的数组,它始终将始终为Array.class
。
you have to pass exact type to get method. 您必须传递确切的类型来获取方法。 If your type is array then you will need to pass something like String[].class - according to the signature provided 如果您的类型是数组,则需要根据提供的签名传递类似String []。class的内容
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.