黑马程序员技术交流社区

标题: 关于list返回具体类型 [打印本页]

作者: 执笔梦    时间: 2014-6-22 16:01
标题: 关于list返回具体类型
本帖最后由 执笔梦 于 2014-6-22 21:14 编辑

比如:
List<A> listA = new ArrayList<A>();
List<B> listB = new ArrayList<B>();

getList(listA);
getList(listB)

public void getListType(List list){
    在这如何获取对应的具体类型,并调用对就的具体类型的方法,


  Method method = list.class.getMethod("get",null);
   Class returnTypeClass = method.getReturnType();
  在这就算知道要获取的类型就是returnTypeClass ,但如何转换为具体对应的类型呢?
   
}
作者: 执笔梦    时间: 2014-6-22 17:25
本帖最后由 执笔梦 于 2014-6-22 17:26 编辑

让我想出来了,我是这样这样实现的..
Method method = list.class.getMethod("get",int.class);
Method method = objList.getClass().getMethod("get",int.class);
Class returnType  =method.invoke(objList, 1).getClass();
if(A.class == returnType){    A  a = (A)list.get(i);
    a.something();
}else if(B.class == returnType){
  B  b = (B)list.get(i);
    b.something();
}

作者: 执笔梦    时间: 2014-6-25 23:24
我看到了版主给我加分了,好激动。。
..我学到了一个更有趣的实现。
Field field = Pair.class.getDeclaredField("myList"); //myList的类型是List
Type type = field.getGenericType();
if (type instanceof ParameterizedType) {     
    ParameterizedType paramType = (ParameterizedType) type;     
    Type[] actualTypes = paramType.getActualTypeArguments();     
    for (Type aType : actualTypes) {         
        if (aType instanceof Class) {         
            Class clz = (Class) aType;            
            System.out.println(clz.getName());   
        }     
    }
}
这只能在本类使用.如果是方法传过来的话,我不知道如何获取mylist所在的类的字节码





欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/) 黑马程序员IT技术论坛 X3.2