class ABC<T>{
Class getCls(){
return T的实际类型;
}
}比如 new ABC<Ingeger>().getCls() 能得到 Integer 类型;请问有没有办法实现这个功能.谢谢
Class getCls(){
return T的实际类型;
}
}比如 new ABC<Ingeger>().getCls() 能得到 Integer 类型;请问有没有办法实现这个功能.谢谢
解决方案 »
- 使用BufferedWriter文件为什么会被清空?
- junit4为什么一次性把所有方法执行光了?
- 最近初学java……不知道java现在是什么行情?大家讨论下……
- jdbc从数据库取出中文数据显示乱码
- 请教各位大虾.有谁知道基于jabber的开源的通讯的客户端吗?
- 关于extends和implements
- 想请教一下键盘监听的问题
- 高手进来分析一下,不知道是不是java 还是 oracle的问题
- 【求助】 redis 实时并列排行榜解决方案
- java调试没有显示空却还是 NullPointerException
- 求教使用JAVA操作word文件的方法
- SWT 中如何保存styledText内样式文本到数据库
T getCls(){
return T的实际类型;
}
}
public static void main(String[] args) {
ABC<Integer> abc = new ABC<Integer>(new Integer(10));
System.out.println(abc.getCls());
}
}class ABC<T> {
public T t;
public T getT() {
return t;
}
public void setT(T t) {
this.t = t;
}
public ABC(T t) {
this.t = t;
}
public ABC() {
}
public Object getCls() {
return t.getClass().getName();
}
}
ABC<Integer> abc = new ABC<Integer>(new Integer(10));
这里传了一个integer的参数进去了,不就等于告诉电脑是integer类型吗...真的很取巧,没有说服力.用无参的构造函数能搞得定吗?
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.HashMap;
public class LM2 {
public static void main(String[] args) throws SecurityException, NoSuchMethodException {
ABC<Integer> abc = new ABC<Integer>();
//通过变量abc无法获得HashMap中的泛型的具体类型,但是当把它传给一个方法后,
//通过该方法就可以得到泛型的实际类型,所以下面随便定义个方法applyAbc,
//其参数是abc,在方法getType中得到泛型的具体类型
getType();
}
public static void applyAbc(ABC<Integer> abc) {
//该方法可以为空
}
/**
* 在该方法中得到泛型的实际类型
*/
public static void getType() throws SecurityException, NoSuchMethodException {
Method m = LM2.class.getMethod("applyAbc", ABC.class);
Type[] type = m.getGenericParameterTypes();
for(int i=0; i<type.length; i++) {
ParameterizedType pt = (ParameterizedType)type[i];
Type[] temp = pt.getActualTypeArguments();
for(int j=0; j<temp.length; j++) {
System.out.println(temp[j]);
}
}
}
}class ABC<T> {
}
public class LM2<T> {
public static void main(String[] args) throws SecurityException, NoSuchMethodException {
System.out.println(new ABC<Integer>().getCls());//输出:class java.lang.Integer
System.out.println(new ABC<String>().getCls());//输出:class java.lang.String
}
}class ABC<T> {
public Class getCls(){
return T的实际类型;
}
}望高手赐教!!!
public Class getCls(){
return T的实际类型;
}
public static void main(String[] args) throws SecurityException, NoSuchMethodException {
System.out.println(new ABC<Integer>().getCls());//输出:class java.lang.Integer
System.out.println(new ABC<String>().getCls());//输出:class java.lang.String
}
}
class java.lang.Integer
class java.lang.Stringimport java.lang.reflect.ParameterizedType;/**
* @author Redduke
*/
public abstract class ABC<T> {
public Class<T> getCls() {
return (Class<T>) ((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[0];
} public static void main(String[] args) {
System.out.println(new ABC<Integer>() {}.getCls());
System.out.println(new ABC<String>() {}.getCls());
}
}
9楼强悍,膜拜ing