public class MainTest { public static void main(String[] args) { Test<String> t = new Test<String>("a"); t.test(); Test<Integer> t1 = new Test<Integer>(1); t1.test(); } }class Test<T> { private T t; public Test(T t) { this.t = t; } public void test() { System.out.println(t.getClass()); } }
correct. Generic is used to help you correct your error while compiling. if you want to get the runtime type. you'll have to think your own ways. for example, to make up a method.
Erasure表现在这里就像这样:public String loophole(Integer x) { List<String> ys = new LinkedList<String>(); List xs = ys; xs.add(x); // compile-time unchecked warning return ys.iterator().next(); }通过类型擦除转化为:public String loophole(Integer x) { List ys = new LinkedList; List xs = ys; xs.add(x); return (String) ys.iterator().next(); // run time error }但是最后强制转换时,String类型信息不是恰恰存在着的嘛,可能没有一种很直接的方式来获得这个信息
哥们 有些问题你想怎么实在?是这样子么? 呵呵 --------------- class User(){ } class MyList<T>{ }public class Test{ public static void main(String)[ MyList<User> us = new MyList(User);// 如何通过us获取 T 的类型?} }
+1,继承的那种方法是因为在编译期,class B extends A<String>, class C extends A<Integer>的信息已经能够获取,明显知道是String/Integer。所以相关的getClass()方法才会带有各自的泛型信息。
public static void main(String[] args) {
Test<String> t = new Test<String>("a");
t.test();
Test<Integer> t1 = new Test<Integer>(1);
t1.test();
}
}class Test<T> {
private T t;
public Test(T t) {
this.t = t;
}
public void test() {
System.out.println(t.getClass());
}
}
http://blog.csdn.net/ykdsg/archive/2010/04/11/5472591.aspx
2楼 方法指标不治本,如果对方提供的方法里面没有响应方法, 那岂不是也无法取到?3楼那篇日志
看了一下
======================
这是泛型擦拭法使得Generic无法获取自己的Generic Type类型。实际上BadClass<String>()实例化以后Class里面就不包括T的信息了,对于Class而言T已经被擦拭为Object,而真正的T参数被转到使用T的方法(或者变量声明或者其它使用T的地方)里面(如果没有那就没有存根),所以无法反射到T的具体类别,也就无法得到T.class。而getGenericSuperclass()是Generic继承的特例,对于这种情况子类会保存父类的Generic参数类型,返回一个ParameterizedType,这时可以获取到父类的T.class了,这也正是子类确定应该继承什么T的方法本文来自CSDN博客,转载请标明出处:http://blog.csdn.net/ykdsg/archive/2010/04/11/5472591.aspx难道获取T.class 就只能通过子类来搞定么?如果不继承就真的没法获取???
List<String> ys = new LinkedList<String>();
List xs = ys;
xs.add(x); // compile-time unchecked warning
return ys.iterator().next();
}通过类型擦除转化为:public String loophole(Integer x) {
List ys = new LinkedList;
List xs = ys;
xs.add(x);
return (String) ys.iterator().next(); // run time error
}但是最后强制转换时,String类型信息不是恰恰存在着的嘛,可能没有一种很直接的方式来获得这个信息
---------------
class User(){
}
class MyList<T>{
}public class Test{
public static void main(String)[
MyList<User> us = new MyList(User);// 如何通过us获取 T 的类型?}
}
+1,继承的那种方法是因为在编译期,class B extends A<String>, class C extends A<Integer>的信息已经能够获取,明显知道是String/Integer。所以相关的getClass()方法才会带有各自的泛型信息。