当List.isempty()==true,如何确定T的类型?

damao74 2009-03-01 10:18:54
class GenericsList<T> {
private List<T> list;


public GenericsList(List<T> list) {
this.list = list;
}

public void getElementClass() {
//此处需要T的类
}
}

public class GenericsListDemo {
public static void main(String args[]) {

List<String> list = new ArrayList<String>();

GenericsList<String> gList = new GenericsList<String>(list);
gList.getElementClass();
}
}
...全文
289 11 打赏 收藏 转发到动态 举报
写回复
用AI写文章
11 条回复
切换为时间正序
请发表友善的回复…
发表回复
dreamhunter_lan 2009-03-02
  • 打赏
  • 举报
回复
不能获得
如果能获得的话就不叫泛型了吧?
liang__ 2009-03-02
  • 打赏
  • 举报
回复
又一个要获得T的类型的,可能是获得不了的。
kukufly 2009-03-02
  • 打赏
  • 举报
回复
不是很明白lz的意思

只能帮你顶一下了
damao74 2009-03-02
  • 打赏
  • 举报
回复
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;

class GenericsList<T> {
private List<T> list;

public GenericsList(List<T> list) {
this.list = list;
getElementClass();
}

public void getElementClass() {
// 此处需要T的类 (return T.class;)
Type type = list.getClass().getGenericSuperclass();
System.out.println(type);
ParameterizedType pType = (ParameterizedType)type;
System.out.println(pType);
Type[] aType = pType.getActualTypeArguments();
System.out.println(aType[0]);
System.out.println(aType[0].getClass());
}

public List<T> getList() {
return list;
}
}

class Dog {
}

class Cat {
}

public class GenericsListDemo {
public static void main(String args[]) {

List<Dog> list1 = new ArrayList<Dog>();

GenericsList<Dog> gList1 = new GenericsList<Dog>(list1);
gList1.getList();

// List<Cat> list2 = new ArrayList<Cat>();
// GenericsList<Cat> gList2 = new GenericsList<Cat>(list2);
// gList2.getList();
}
}
庚武讲堂 2009-03-02
  • 打赏
  • 举报
回复
晕,没看标题,isEmpty()==true了,看样子我的不行
庚武讲堂 2009-03-02
  • 打赏
  • 举报
回复
if(list.size>0){
if(list.get(0) instanceof String){
//你的操作

}
else if(list.get(0) instanceof xxx){
//你的操作

}
}

试试这个吧,没调试的
ouyangxiaokang6 2009-03-02
  • 打赏
  • 举报
回复
你既然用了泛型,就是你传递的类型是不确定的。
goodmrning 2009-03-01
  • 打赏
  • 举报
回复
不明白LZ什么意思
不善^ 2009-03-01
  • 打赏
  • 举报
回复
String
damao74 2009-03-01
  • 打赏
  • 举报
回复
强调一下,我需要的是T的类(class),不是标识
如用于:spring.getHibernateTemplate().loadAll(T.class);
rypgood 2009-03-01
  • 打赏
  • 举报
回复
直接用T就行了
for(T t:list)
{
^^^^^^^^
}

62,628

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧