黑马程序员技术交流社区
标题:
求解通过反射获取随机引用泛型类类型变量的问题??
[打印本页]
作者:
yufeng47
时间:
2013-4-9 14:34
标题:
求解通过反射获取随机引用泛型类类型变量的问题??
本帖最后由 yufeng47 于 2013-4-19 08:41 编辑
package cn.itcast.day2;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.lang.reflect.TypeVariable;
import java.util.ArrayList;
import java.util.Collection;
public class GenericQuestion {
/**
* @param args
* @throws Exception
*/
public static void main(String[] args) throws Exception {
ArrayList<String> collection1 = new ArrayList<String>();
Collection<? extends Number> collection2 = new ArrayList<Byte>();
getCollectionTypeOfParameter(collection1);
getCollectionTypeOfParameter(collection2);
}
/* 用反射方式获取参数列表中类型变量*/
public static void getCollectionTypeOfParameter(Collection<?> src)
throws Exception{
TypeVariable<?>[] typeVariable = src.getClass().getTypeParameters();
// 获取引用的通用声明(GetGenericDeclaration)的类型变量(API中对其声明的类型变量)
System.out.println(typeVariable[0].getGenericDeclaration());
// 获取引用的类型
System.out.println(typeVariable[0].getName());
// 获取类型变量的上边界,上边界一般为Object(除非<? extends Number>,则为Number)
Type[] type = typeVariable[0].getBounds();
System.out.println(type[0]);
// 获取方法的原始参数类及其类型变量
Type[] types = GenericQuestion.class.getMethod
("getCollectionTypeOfParameter", Collection.class).getGenericParameterTypes();
ParameterizedType typeOfParameter = (ParameterizedType)types[0];
System.out.println(typeOfParameter.getRawType()); //原始参数类型
System.out.println(typeOfParameter.getActualTypeArguments()[0]);//类型参数
}
}
复制代码
/*
由于java中泛型是用于编译器行类型检查和类型推断的,在正式运行生成原始类的字节码时会用擦除技术抹去,
所以貌似不可能实现获取引用的实例化类型参数。不过还是要问哈童鞋们,这种方式能实现么?即上述方法中
如果传入的引用类型是ArrayList<String>,能否就得到原始类 ArrayList和类型变量String呢?
*/
作者:
王洪宇
时间:
2013-4-14 10:26
package com.test;
import java.lang.reflect.Method;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.ArrayList;
public class Test1 {
//声明一个传入ArrayList<String>类型参数的方法,不需要方法体
public static void noUse(ArrayList<String> alist){}
public static void main(String[] args) throws Exception{
//通过反射得到刚刚声明的方法
Method method = Test1.class.getMethod("noUse",ArrayList.class);
//得到这个方法的参数列表
Type[] types = method.getGenericParameterTypes();
//如果第一个参数是参数化类型,下面就好办了
if(types[0] instanceof ParameterizedType){
ParameterizedType pType = (ParameterizedType)types[0];
Type[] temp = pType.getActualTypeArguments();
System.out.println(temp[0]);//输出:class java.lang.String
}
}
}
复制代码
刚刚翻了半天资料,终于找到了一种解决方案。
看看对你有没有用。
作者:
刘印12
时间:
2013-4-14 11:35
na shi 必须能的 多看一些张孝祥老师的视频把
作者:
yufeng47
时间:
2013-4-19 08:39
王洪宇 发表于 2013-4-14 10:26
刚刚翻了半天资料,终于找到了一种解决方案。
看看对你有没有用。
虽然不是我想要的,但是还是谢谢。
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2