输出为
class java.util.HashMap class java.lang.String class java.lang.Integer =====newclass===== class java.util.AbstractMap K V =====subclass===== class java.util.HashMap class java.lang.String class java.lang.Integer
获取到了实际类型,就可实现对泛型的反序列化。
Java虽然运行时会有类型擦除,但会保留Field的泛型信息,可通过Field.getGenericType()
取字段的泛型。
public class FieldGenericKest { public Map<String,Integer> map = new HashMap<>(); public List<Long> list = new ArrayList<>(); public static void main(String[] args) throws Exception { FieldGenericKest kest = new FieldGenericKest(); Field map = kest.getClass().getField("map"); Field list = kest.getClass().getField("list"); System.out.println("=====map====="); System.out.println("map.getType=" + map.getType()); System.out.println("map.getGenericType=" + map.getGenericType()); System.out.println("=====list====="); System.out.println("list.getType=" + list.getType()); System.out.println("list.getGenericType=" + list.getGenericType()); } }
输出
=====map===== map.getType=interface java.util.Map map.getGenericType=java.util.Map<java.lang.String, java.lang.Integer> =====list===== list.getType=interface java.util.List list.getGenericType=java.util.List<java.lang.Long>
注意这里不能获取到字段的真实类型HashMap和ArrayList。
真实的类型当然不能用Field来获取,需要用对应的Value来获取
Object mapVal = map.get(kest); if(mapVal != null){ Class<?> clz = mapVal.getClass(); System.out.println(mapVal.getClass().getName()); }
因为泛型的运行时擦除,对于局部变量来说, 泛型信息是无法获取的
参考
http://www.java2s.com/Tutorials/Java/java.lang/Class/Java_Class_getGenericSuperclass_.htm
https://zhaoyanblog.com/archives/186.html
https://developer.aliyun.com/article/609441