Last active
September 21, 2017 13:08
-
-
Save thinkerzhangyan/68c65f4076c386b9a5bb756d45932d9d to your computer and use it in GitHub Desktop.
GenericTest
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.*; | |
import java.lang.reflect.*; | |
public class GenericTest | |
{ | |
private Map<String , Integer> score; | |
public static void main(String[] args) throws Exception | |
{ | |
Class<GenericTest> clazz = GenericTest.class; | |
Field f = clazz.getDeclaredField("score"); | |
// 直接使用getType()取出Field类型只对普通类型的Field有效 | |
Class<?> a = f.getType(); | |
// 下面将看到仅输出java.util.Map | |
System.out.println("score的类型是:" + a); | |
// 获得Field实例f的泛型类型 | |
Type gType = f.getGenericType(); | |
// 如果gType类型是ParameterizedType对象 | |
if(gType instanceof ParameterizedType) | |
{ | |
// 强制类型转换 | |
ParameterizedType pType = (ParameterizedType)gType; | |
// 获取原始类型 | |
Type rType = pType.getRawType(); | |
System.out.println("原始类型是:" + rType); | |
// 取得泛型类型的泛型参数 | |
Type[] tArgs = pType.getActualTypeArguments(); | |
System.out.println("泛型类型是:"); | |
for (int i = 0; i < tArgs.length; i++) | |
{ | |
System.out.println("第" + i + "个泛型类型是:" + tArgs[i]); | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment