文章来源:http://www.blogjava.net/dreamstone/archive/2007/02/10/99194.html
Tags: 泛型泛型 | 反射反射
2007-2-10 23:36:06 | 编辑
利用反射取得泛型信息
一、传统通过反射取得函数的参数和返回值
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()函数的参数,就可以对应上边的问题了。