java中取泛型对象

1.方案1:没有继承关系的

public class A<T> {    
Class<T> clazz;
public A(T... ts){
this. clazz = getTClass(ts);
}
static <T> Class<T> getTClass(@SuppressWarnings("unchecked") T... index) {
        String name = "[Ljava.lang.Object;";
        if (index != null)// 如果index参数不为空
            name = index.getClass().getName();// 根据index找到对应类型(数组)的名称
        StringBuffer sbf = new StringBuffer();
        for (int i = 2; i < name.length() - 1; i++)// 循坏重新放置到sbf里面
            sbf.append(name.charAt(i));
        name = sbf.toString();// 更新name变量
        try {
            return (Class<T>)Class.forName(name);// 若不出错,class存在即返回Class<?>
        } catch (ClassNotFoundException e) {
            System.err.println(e.getMessage());// 若出错,class不存在即返回null
        }
        return null;
    }
}

  

2.方案2:存在继承关系

 public class DbAccess<T> implements IDbAccess<T> {

private Class<T> getTClass() {
Class<T> tClass = (Class<T>) ((ParameterizedType) getClass().getGenericSuperclass())
.getActualTypeArguments()[0];
return tClass;
}
}
原文地址:https://www.cnblogs.com/liucuiqiang/p/11595685.html