1、過程
(1)測試屬性類型
(2)列印type與generic type的區別
(3)測試參數類型
(4)測試傳回值類型
2、實例
public class Client { private Map<String, Object> objectMap; public void test(Map<String, User> map, String string) { } public Map<User, Bean> test() { return null; } /** * 测试属性类型 * * @throws NoSuchFieldException */ @Test public void testFieldType() throws NoSuchFieldException { Field field = Client.class.getDeclaredField("objectMap"); Type gType = field.getGenericType(); // 打印type与generic type的区别 System.out.println(field.getType()); System.out.println(gType); System.out.println("**************"); if (gType instanceof ParameterizedType) { ParameterizedType pType = (ParameterizedType) gType; Type[] types = pType.getActualTypeArguments(); for (Type type : types) { System.out.println(type.toString()); } } } /** * 测试参数类型 * * @throws NoSuchMethodException */ @Test public void testParamType() throws NoSuchMethodException { Method testMethod = Client.class.getMethod("test", Map.class, String.class); Type[] parameterTypes = testMethod.getGenericParameterTypes(); for (Type type : parameterTypes) { System.out.println("type -> " + type); if (type instanceof ParameterizedType) { Type[] actualTypes = ((ParameterizedType) type).getActualTypeArguments(); for (Type actualType : actualTypes) { System.out.println("\tactual type -> " + actualType); } } } } /** * 测试返回值类型 * * @throws NoSuchMethodException */ @Test public void testReturnType() throws NoSuchMethodException { Method testMethod = Client.class.getMethod("test"); Type returnType = testMethod.getGenericReturnType(); System.out.println("return type -> " + returnType); if (returnType instanceof ParameterizedType) { Type[] actualTypes = ((ParameterizedType) returnType).getActualTypeArguments(); for (Type actualType : actualTypes) { System.out.println("\tactual type -> " + actualType); } } } }
以上是Java中ParameterizedType的使用方法與實作方式的詳細內容。更多資訊請關注PHP中文網其他相關文章!