
本教程操作环境:windows7系统、java10版,DELL G3电脑。
1、过程
(1)测试属性类型
(2)打印type与generic type的区别
(3)测试参数类型
(4)测试返回值类型
2、实例
publicclassClient{
privateMap<String,Object>objectMap;
publicvoidtest(Map<String,User>map,Stringstring){
}
publicMap<User,Bean>test(){
returnnull;
}
/**
*测试属性类型
*
*@throwsNoSuchFieldException
*/
@Test
publicvoidtestFieldType()throwsNoSuchFieldException{
Fieldfield=Client.class.getDeclaredField("objectMap");
TypegType=field.getGenericType();
//打印type与generictype的区别
System.out.println(field.getType());
System.out.println(gType);
System.out.println("**************");
if(gTypeinstanceofParameterizedType){
ParameterizedTypepType=(ParameterizedType)gType;
Type[]types=pType.getActualTypeArguments();
for(Typetype:types){
System.out.println(type.toString());
}
}
}
/**
*测试参数类型
*
*@throwsNoSuchMethodException
*/
@Test
publicvoidtestParamType()throwsNoSuchMethodException{
MethodtestMethod=Client.class.getMethod("test",Map.class,String.class);
Type[]parameterTypes=testMethod.getGenericParameterTypes();
for(Typetype:parameterTypes){
System.out.println("type->"+type);
if(typeinstanceofParameterizedType){
Type[]actualTypes=((ParameterizedType)type).getActualTypeArguments();
for(TypeactualType:actualTypes){
System.out.println("\tactualtype->"+actualType);
}
}
}
}
/**
*测试返回值类型
*
*@throwsNoSuchMethodException
*/
@Test
publicvoidtestReturnType()throwsNoSuchMethodException{
MethodtestMethod=Client.class.getMethod("test");
TypereturnType=testMethod.getGenericReturnType();
System.out.println("returntype->"+returnType);
if(returnTypeinstanceofParameterizedType){
Type[]actualTypes=((ParameterizedType)returnType).getActualTypeArguments();
for(TypeactualType:actualTypes){
System.out.println("\tactualtype->"+actualType);
}
}
}
}原文来自:https://www.py.cn © 版权声明
文章版权归作者所有,未经允许请勿转载。
THE END
















































暂无评论内容