public class testclass{
public <T> void test(){
//如何获取T的真正类型,test没有参数
System.out.println("T的类型"+"........")
}
}
public class testGeneric {
public static void main(String args[]){
testclass s=new testclass();
s.<String>test();
}
}
解决方案 »
- 为什么用cfx做webservice时,参数名不会显示在wsdl中, 只显示"<soap:body use="literal"/>"
- myeclipse问题
- I/O Error: Connection reset这是什么问题
- AJAX高手请进(重金酬谢)
- 网页中嵌入mfc客户端程序(顶者有分)
- 求助,jsp数据库导出到word中如何将页面设置成横向来打印?
- 我要问一个JSP里的问题啊!!!!!急
- 提交表单问题续集!
- apache如何配置?
- huyuefox,谢谢你的代码,这20分给你
- java.util中的map接口是怎么回事儿!希望大家能够指导!
- org.dom4j.DocumentException这个异常谁能解决?
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;public class Generic extends Base<String> {
public static void main(String[] args) {
Generic c = new Generic();
System.out.println(c.array);
}
Object array ;
public Generic() {
array = Array.newInstance(getGenericType(0), 100);
}
}class Base<T> {
public Class getGenericType(int index) {
Type genType = getClass().getGenericSuperclass();
if (!(genType instanceof ParameterizedType)) {
return Object.class;
}
Type[] params = ((ParameterizedType) genType).getActualTypeArguments();
if (index >= params.length || index < 0) {
throw new RuntimeException("Index outof bounds");
}
if (!(params[index] instanceof Class)) {
return Object.class;
}
return (Class) params[index];
}
}
这是百度知道里的回答,看看吧!~
LS给的例子和LZ的需求是不一样的,因为是子类继承了类,子类用具体的类型代替了泛型,如果LS的例子改成
public class Generic extends Base<T> //这里还是泛型,一样拿不到String,这里的区别很重要LZ好好体会一下这个例子
public class testclass {
public <T, E> void test() {
try {
Class<?> c = this.getClass();
Method m = c.getDeclaredMethod("test");
for (TypeVariable tv : m.getTypeParameters()) {
System.out.println(tv);
for (Type t : tv.getBounds()) {
System.out.println(t);
}
}
} catch (Exception e) {
e.printStackTrace();
}
} public static void main(String[] args) {
testclass tc = new testclass();
tc.<String, Integer>test();
}
}
为什么只能拿到Object,因为只有一个testclass.class文件,而该文件的T和E被擦除为Object,而不存在T和E被替换为String和Integer的class文件,所以不可能取到String和Integer,因为能取到的信息只限于testclass.class的信息,testclass.class里有的是什么,取出来的就是什么。
public <T> void test(Class<T> clazz) //通过参数来指定类型调用
s.<String>test(String.class); //这样来调用