利用反射取得泛型信息

利用反射取得泛型信息

一、传统通过反射取得函数的参数和返回值
import java.lang.reflect.Method;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Map;
import java.util.List;
import java.util.Set;


import sun.reflect.generics.reflectiveObjects.ParameterizedTypeImpl;

public class Foo {
public static void main(String[] args) throws Exception {
Method[] methods = Foo. class .getDeclaredMethods();
for (Method method : methods) {
Class[] paramTypeList = method.getParameterTypes();

Class returnType = method.getReturnType();
System.out.println(returnType);
for (Class clazz:paramTypeList) {
System.out.println(clazz);
}
System.out.println();
}
}
public static String test1(String str) {
return null ;
}
public static Integer test2(String str,Integer i) {
return null ;
}

}


二、在有泛型的时候,取得参数和返回值的集合类的泛型信息
import java.lang.reflect.Method;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Map;
import java.util.List;
import java.util.Set;

import sun.reflect.generics.reflectiveObjects.ParameterizedTypeImpl;

public class Foo {
public static void main(String[] args) throws Exception {
Method[] methods = Foo. class .getDeclaredMethods();
for (Method method : methods) {
System.out.println( " returnType: " );
Type returnType = method.getGenericReturnType();
if (returnType instanceof ParameterizedType) {
Type[] types = ((ParameterizedType)returnType).getActualTypeArguments();
for (Type type:types) {
System.out.println(type);
}
}
System.out.println( " paramTypeType: " );
Type[] paramTypeList = method.getGenericParameterTypes();
for (Type paramType : paramTypeList) {
if (paramType instanceof ParameterizedType) {
Type[] types = ((ParameterizedType)paramType).getActualTypeArguments();
for (Type type:types) {
System.out.println(type);
}
}
}
}
}

public static List < String > test3(List < Integer > list) {
return null ;
}

private static Map < String, Double > test4(Map < String, Object > map) {
return null ;
}

}

三、应用环境
例如你要写一个程序,需求把一个如下的配置文件变成一个集合类。
< config name = " Foo.DoubleBean " >
< element key = " key1 " value = " 1.1 " />
< element key = " key2 " value = " 2.2 " />
< element key = " key3 " value = " 3.3 " />
</ config >

根据用户的参数变成不同的集合类 Map<String.String> Map<String,Double> Map<String,Float>
如果你要着手开发一个框架,这样的需求会比较常见。这个时候取到setXX()函数的参数,就可以对应上边的问题了。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值