JAVA中parameterized,java使用ParameterizedType实现泛型

JAVA中parameterized,java使用ParameterizedType实现泛型1 过程 1 测试属性类型 2 打印 type 与 generictype 的区别 3 测试参数类型 4 测试返回值类型 2 实例 publicclassC privateMapob publicvoidte Mapmap Stringstring publicMaptes returnnull 测试属性类型 throws

1f99d017e047d4c102d59c5f9b8fb28e.png

1、过程

(1)测试属性类型

(2)打印type与generic type的区别

(3)测试参数类型

(4)测试返回值类型

2、实例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);

}

}

}

}

以上就是java使用ParameterizedType实现泛型的方法,希望能对大家有所帮助。更多Java学习指路:

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请联系我们举报,一经查实,本站将立刻删除。

发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/233078.html原文链接:https://javaforall.net

(0)
全栈程序员-站长的头像全栈程序员-站长


相关推荐

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

关注全栈程序员社区公众号