在使用反射機制時,我們經常需要知道方法的參數和返回值類型,很簡單 ,下面上示例,示例中的兩個方法非常相似
package deadLockThread;
import java.lang.reflect.*;
import java.util.*;
public class ParmReturnType {
public static void main(String[] args) throws NoSuchMethodException, SecurityException {
// 獲取指定方法的返回值泛型信息
System.out.println("----------test02獲取返回值類型-------------");
Method method = ParmReturnType.class.getMethod("test02", null);// 根據方法名和參數獲取test02方法
Type type = method.getGenericReturnType();// 獲取返回值類型
if (type instanceof ParameterizedType) { // 判斷獲取的類型是否是參數類型
System.out.println(type);
Type[] typesto = ((ParameterizedType) type).getActualTypeArguments();// 強制轉型為帶參數的泛型類型,
// getActualTypeArguments()方法獲取類型中的實際類型,如map<String,Integer>中的
// String,integer因為可能是多個,所以使用數組
for (Type type2 : typesto) {
System.out.println("泛型類型" + type2);
}
}
System.out.println("------------------------------------------------------");
// 獲取指定方法的參數泛型信息
System.out.println("----------獲取指定方法的參數泛型信息-------------");
Method methodtwo = ParmReturnType.class.getMethod("test01", Map.class, List.class);
Type[] types = methodtwo.getGenericParameterTypes();// 獲取參數,可能是多個,所以是數組
for (Type type2 : types) {
if (type2 instanceof ParameterizedType)// 判斷獲取的類型是否是參數類型
{
System.out.println("-------------------------------------------------");
System.out.println(type);
Type[] typetwos = ((ParameterizedType) type2).getActualTypeArguments();// 強制轉型為帶參數的泛型類型,
// getActualTypeArguments()方法獲取類型中的實際類型,如map<String,Integer>中的
// String,integer因為可能是多個,所以使用數組
for (Type type3 : typetwos) {
System.out.println("參數類型" + type3);
}
}
}
}
// 帶參數的方法Test01
public static void test01(Map<String, Integer> map, List<User> list) {
}
// 帶返回值的方法Test02
public static Map<String, Integer> test02() {
return null;
}
}
