[英]How do I get typeArguments from a List<T> returned by object.getClass().getDeclaredField(“fieldname”).getGenericType();
我正在處理此問題大約2天,但仍然無法解決。 我有這個方法:
public List<T> findByKeyValue(String key, String value, Object t) {
Field field;
Class<?> clazz = t.getClass();
field = clazz.getDeclaredField(key);
Type type = field.getType();
if(type.equals(List.class)) {
// HERE IS THE PROBLEM, the value of "field" is "public java.util.List com.cacobr.model.Video.categoryCollection" and categoryCollection is a List <Category>
// **I need to get the class "Category" with Reflection**
// The "field.getGenericType()" command returns "java.util.List <com.cacobr.model.Category>"
// If I could use something like ".getActualTypeArguments()[0]" could return the class "Category" but I can't use this method after a "getGenericType()"
....
}
我可以上課類別嗎?
您應該可以將其轉換為ParameterizedType
:
Type type = field.getGenericType();
if (type instanceof ParameterizedType) {
ParamterizedType pt = (ParameterizedType) type;
if (pt.getRawType() == List.class &&
pt.getActualTypeArguments()[0] == Category.class) {
...
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.