Reputation: 1533
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 ?
Upvotes: 1
Views: 748
Reputation: 1785
you could simulate with isAssignableFrom
, to check first element and then cast the whole 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;
}
}
Upvotes: 0
Reputation: 73578
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. What are you trying to do?
Upvotes: 0
Reputation: 94499
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.
See: http://docs.oracle.com/javase/tutorial/java/generics/erasure.html
Upvotes: 3