1. 程式人生 > >Java泛型 通過反射獲得方法引數中的變數類名和泛型

Java泛型 通過反射獲得方法引數中的變數類名和泛型

通過反射獲得方法引數中的變數類名和泛型

package test;

import java.lang.reflect.Method;
import java.lang.reflect.ParameterizedType;
import java.util.ArrayList;

public class MainTest {
	public static void main(String[] args) throws Exception {
		ArrayList<String> a = new ArrayList<String>();
		Method applyMethod = MainTest.class.getMethod("applyMethod", ArrayList.class);
		//applyMethod.invoke(null, a);
		ParameterizedType pt = (ParameterizedType) applyMethod.getGenericParameterTypes()[0];
		System.out.println(pt.getRawType());				//ArrayList
		System.out.println(pt.getActualTypeArguments()[0]); //String
	}
	
	public static void applyMethod(ArrayList<String> a) {
		
	}
}