泛型——反射來獲取泛型資訊
阿新 • • 發佈:2019-02-05
package cn_itcast02;
import java.lang.reflect.Field;
import java.lang.reflect.Parameter;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.HashMap;
import java.util.Map;
public class Demo1 {
Map<String, Integer> map = new HashMap<String, Integer>();
public static void main(String[] args) throws NoSuchFieldException,
SecurityException {
Class c = Demo1.class;
Field f = c.getDeclaredField("map");
System.out.println(f);
System.out.println(f.getName());
Class c1=f.getType();
System.out.println(c1);//獲得其型別:interface java.util.Map
Type t=f.getGenericType();//包含泛型的型別
System.out.println(t);//java.util.Map<java.lang.String, java.lang.Integer>
ParameterizedType pt=(ParameterizedType)t;
t=pt.getRawType();
System.out.println(t);//ParameterizedType
Type[]ts=pt.getActualTypeArguments();
for(Type type:ts){
System.out.println(type);//class java.lang.String,class java.lang.Integer
}
}
}
import java.lang.reflect.Field;
import java.lang.reflect.Parameter;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.HashMap;
import java.util.Map;
public class Demo1 {
Map<String, Integer> map = new HashMap<String, Integer>();
public static void main(String[] args) throws NoSuchFieldException,
SecurityException {
Class c = Demo1.class;
Field f = c.getDeclaredField("map");
System.out.println(f);
System.out.println(f.getName());
Class c1=f.getType();
System.out.println(c1);//獲得其型別:interface java.util.Map
Type t=f.getGenericType();//包含泛型的型別
System.out.println(t);//java.util.Map<java.lang.String, java.lang.Integer>
ParameterizedType pt=(ParameterizedType)t;
t=pt.getRawType();
System.out.println(t);//ParameterizedType
Type[]ts=pt.getActualTypeArguments();
for(Type type:ts){
System.out.println(type);//class java.lang.String,class java.lang.Integer
}
}
}