A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

© 执笔梦 金牌黑马   /  2014-6-22 16:01  /  1055 人查看  /  2 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

本帖最后由 执笔梦 于 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 ,但如何转换为具体对应的类型呢?
   
}

评分

参与人数 1技术分 +1 收起 理由
李小然 + 1

查看全部评分

2 个回复

倒序浏览
本帖最后由 执笔梦 于 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();
}
回复 使用道具 举报
我看到了版主给我加分了,好激动。。
..我学到了一个更有趣的实现。
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所在的类的字节码
回复 使用道具 举报
您需要登录后才可以回帖 登录 | 加入黑马