How is an instance of List <MyType>?

How can I make this work work? I can check if (obj instanceof List<?>) , But not if (obj instanceof List<MyType>) . Is there any way to do this?

+49
java generics
Apr 11 2018-12-12T00:
source share
6 answers

This is not possible because erasing the data type during compilation of generics. The only possible way to do this is to write some kind of wrapper that contains a type that has a list:

 public class GenericList <T> extends ArrayList<T> { private Class<T> genericType; public GenericList(Class<T> c) { this.genericType = c; } public Class<T> getGenericType() { return genericType; } } 
+33
Apr 11 2018-12-12T00:
source share
— -
 if(!myList.isEmpty() && myList.get(0) instanceof MyType){ // MyType object } 
+16
Jul 23 '16 at 8:46
source share

You probably need to use reflection to check their types. To get the list type: Get the general type java.util.List

+8
Apr 11 2018-12-12T00:
source share

If you check if the reference of a List or Map object is an instance of a collection, just create an instance of the desired list and get its class ...

 Set<Object> setOfIntegers = new HashSet(Arrays.asList(2, 4, 5)); assetThat(setOfIntegers).instanceOf(new ArrayList<Integer>().getClass()); Set<Object> setOfStrings = new HashSet(Arrays.asList("my", "name", "is")); assetThat(setOfStrings).instanceOf(new ArrayList<String>().getClass()); 
0
Jan 15 '17 at 2:27
source share

If it is impossible to wrap using generics (@ Martijn answer), it is better to pass it without a cast to avoid excessive iteration of the list (checking the first type of an element does not guarantee anything). We can use every element in the code fragment where we iterate over the list.

 Object attVal = jsonMap.get("attName"); List<Object> ls = new ArrayList<>(); if (attVal instanceof List) { ls.addAll((List) attVal); } else { ls.add(attVal); } // far, far away ;) for (Object item : ls) { if (item instanceof String) { System.out.println(item); } else { throw new RuntimeException("Wrong class ("+item .getClass()+") of "+item ); } } 
0
Apr 7 '17 at 14:12
source share

You can use a fake factory to include many methods instead of using instanceof:

 public class Message1 implements YourInterface { List<YourObject1> list; Message1(List<YourObject1> l) { list = l; } } public class Message2 implements YourInterface { List<YourObject2> list; Message2(List<YourObject2> l) { list = l; } } public class FactoryMessage { public static List<YourInterface> getMessage(List<YourObject1> list) { return (List<YourInterface>) new Message1(list); } public static List<YourInterface> getMessage(List<YourObject2> list) { return (List<YourInterface>) new Message2(list); } } 
0
Oct 24 '17 at 11:09 on
source share



All Articles