一、傳統(tǒng)通過(guò)反射取得函數(shù)的參數(shù)和返回值
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 ;
}
}
二、在有泛型的時(shí)候,取得參數(shù)和返回值的集合類的泛型信息
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 ;
}
}
三、應(yīng)用環(huán)境
例如你要寫(xiě)一個(gè)程序,需求把一個(gè)如下的配置文件變成一個(gè)集合類。
< config name = " Foo.DoubleBean " >
< element key = " key1 " value = " 1.1 " />
< element key = " key2 " value = " 2.2 " />
< element key = " key3 " value = " 3.3 " />
</ config > 根據(jù)用戶的參數(shù)變成不同的集合類 Map<String.String> Map<String,Double> Map<String,Float>
如果你要著手開(kāi)發(fā)一個(gè)框架,這樣的需求會(huì)比較常見(jiàn)。這個(gè)時(shí)候取到setXX()函數(shù)的參數(shù),就可以對(duì)應(yīng)上邊的問(wèn)題了。
(#)
本站僅提供存儲(chǔ)服務(wù),所有內(nèi)容均由用戶發(fā)布,如發(fā)現(xiàn)有害或侵權(quán)內(nèi)容,請(qǐng)
點(diǎn)擊舉報(bào)。