Java – check whether the object is an instance of list
•
Java
I have an object that sometimes contains list < Object > I want to check it with instanceof, and if so, add some elements
void add(Object toAdd) { Object obj = getValue(); if (obj instanceof List<?>) { List<?> list = obj; if (list instanceof List<Object>) { // Error ((List<Object>) list).add(toAdd); } else { List<Object> newList = new ArrayList<Object>(list); newList.add(toAdd); setValue(newList); } return; } throw new SomeException(); }
It says I can't check whether it is an instance of list < Object >, because Java doesn't care and deletes the types in < > Does this mean that I have to create a new ArrayList every time? Or is there any way to check, for example With reflection?
Solution
My previous answer was wrong because I didn't fully understand your request
void add(Object toAdd) { Object obj = getObject(); if (obj instanceof List<?>) { ((List<Object>)obj).add(toAdd); return; } throw new SomeException(); }
UPDATE
As the answer to several comments, there is no problem adding any object to the list, and there is no problem finding out what type of object it is after iteration:
List<String> x1 = new ArrayList<String>(); Object c3 = x1; x1.add("asdsad"); Integer y2 = new Integer(5); if (c3 instanceof List<?>){ ((List<Object>)c3).add((Object)y2); } for (Object i : (List<Object>)c3){ if (i instanceof String){ System.out.println("String: " + (String)i); } if (i instanceof Integer){ System.out.println("Integer: "+ (Integer)i); } }
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码