Home> Java> javaTutorial> body text

How to use and implement ParameterizedType in Java

PHPz
Release: 2023-04-25 15:46:07
forward
950 people have browsed it

1. Process

(1) Test attribute type

(2) The difference between print type and generic type

(3) Test Parameter type

(4) Test return value type

2, instance

public class Client { private Map objectMap; public void test(Map map, String string) { } public Map 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); } } } }
Copy after login

The above is the detailed content of How to use and implement ParameterizedType in Java. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:yisu.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!