- Java code
public class testclass{ public <T> void test(){ //如何获取T的真正类型,test没有参数 System.out.println("T的类型"+"........") }}
- Java code
public class testGeneric { public static void main(String args[]){ testclass s=new testclass(); s.<String>test(); }}
------解决方案--------------------------------------------------------
import java.lang.reflect.Array;
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];
}
}
这是百度知道里的回答,看看吧!~
------解决方案--------------------------------------------------------
这个问题很多人问过了,这个思路走不通的.
对于testclass.class来说,编译的字节码里面的T信息被转换成Object,也就是说testclass.class里面只有Object信息,所以s.<String>test();这里的String传到testclass.class里也被转成了Object,所以你只能拿到Object信息,拿不到String信息。
LS给的例子和LZ的需求是不一样的,因为是子类继承了类,子类用具体的类型代替了泛型,如果LS的例子改成
public class Generic extends Base<T> //这里还是泛型,一样拿不到String,这里的区别很重要
LZ好好体会一下这个例子
- Java code
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(); }}
------解决方案--------------------------------------------------------
楼上正解++