基本使用
public class FetchGenericItem {
private Collection<String> names;
public static void main(String[] args) throws Exception {
FetchGenericItem fetchGenericItem = new FetchGenericItem();
//場(chǎng)景1:獲取成員變量的泛型元素
Field field = fetchGenericItem.getClass().getDeclaredField("names");
System.out.println(fetchGenericItem.getActualTypeFieldType(field.getGenericType()));//class java.lang.String
//場(chǎng)景2:獲取方法參數(shù)的泛型元素
Method method = fetchGenericItem.getClass().getDeclaredMethod("setNames", Collection.class);
Type[] genericParameterTypes = method.getGenericParameterTypes();
for (Type genericParameterType : genericParameterTypes) {
System.out.println(fetchGenericItem.getActualTypeFieldType(genericParameterType));//class java.lang.String
}
}
public FetchGenericItem setNames(Collection<String> names) {
this.names = names;
return this;
}
/**
* 獲取泛型類型
*/
private Type getActualTypeFieldType(Type elType) {
if (elType instanceof ParameterizedType) {
ParameterizedType parameterizedType = (ParameterizedType) elType;
Type[] types = parameterizedType.getActualTypeArguments();
if (types.length == 1)
return parameterizedType.getActualTypeArguments()[0];
else
return null;
} else
return null;
}
}
Type
type類型是所有類型的父類