[英]How can I get parameter Type from generic list in Java?
I have code like this : 我有这样的代码:
List<TRt> listTrt;
List<TRtKuesioner> listTrtKuesioner;
List<TArtKuesioner> listTArtKuesioner;
Object[] objects = new Object[] {
listTrt, listTrtKuesioner,listTArtKuesioner
};
How can I do function like my wish below : 我怎样才能像下面的愿望那样运作:
for(Object o :objects){
if(o instanceof List<TRt>){
}else if(o instanceof List<TRtKuesioner>){
}else if(o instanceof List<TArtKuesioner>){
}
}
How I can accomplish this ? 我怎么能做到这一点?
The type arguments of a generic type are not available at runtime due to a process known as type erasure. 由于称为类型擦除的过程,泛型类型的类型参数在运行时不可用。 In a nutshell, type erasure is the process by which the compiler removes type arguments and replaces the with casts where appropriate. 简而言之,类型擦除是编译器删除类型参数并在适当时替换with转换的过程。
See: http://docs.oracle.com/javase/tutorial/java/generics/erasure.html 请参阅: http : //docs.oracle.com/javase/tutorial/java/generics/erasure.html
Provided that the lists are non-empty, you could simulate it with 如果列表非空,您可以使用它进行模拟
if(((List)o).get(0) instanceof TRt)
but a better idea would be to try to avoid the Object array completely. 但更好的想法是尝试完全避免Object数组。 What are you trying to do? 你想做什么?
you could simulate with isAssignableFrom
, to check first element and then cast the whole List. 您可以使用isAssignableFrom
进行模拟,以检查第一个元素,然后转换整个List。
ex : 例如:
public static void main(String[] args) throws Exception {
List<String> strings = new ArrayList<String>();
strings.add("jora string");
List<Integer> ints = new ArrayList<Integer>();
ints.add(345);
Object[] objs = new Object[]{strings,ints};
for (Object obj : objs){
if (isListInstanceOf(obj, String.class)){
List<String> strs = castListTo(obj, String.class);
for (String str : strs){
System.out.println(str);
}
}else if (isListInstanceOf(obj, Integer.class)){
List<Integer> inList = castListTo(obj, Integer.class);
for (Integer integ : inList){
System.out.println("Int: "+integ);
}
}
}
}
public static boolean isListInstanceOf(Object list, Class clazz){
return (list instanceof List && ((List)list).size() > 0) ? ((List)list).get(0).getClass().isAssignableFrom(clazz) : false;
}
public static <T> List<T> castListTo(Object list, Class<T> clazz){
try{
return (List<T>)list;
}catch(ClassCastException exc){
System.out.println("can't cast to that type list");
return null;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.