0

Say I have a method that accepts an instance of a java Object (Java.lang.Object) as a parameter. Is there a way of determining if this passed in Object is an array (of anything) and then iterating over it?

This is what I'm currently trying to do

public static void isThisAnArray(Object x) {
     if (x instanceof Object[]){
         for (Object item : x) {
             //do something with item
         }
     }
}

But I get "Can only iterate over an array or an instance of java.lang.Iterable" on the for (Object item : x) line Which makes sense, since I'm passing in an Object and not an array of Objects. But what if that object is an array of objects? Sorry if this is confusing but is there a way to figure out if a passed in java object is an array?

Andy Turner
  • 137,514
  • 11
  • 162
  • 243
  • I dont get your question. Does the above code give that error message? Or could it be that you determine "it is an array" but then do **not** cast to array before using it? – GhostCat May 30 '19 at 18:56
  • 2
    See https://stackoverflow.com/questions/219881/java-array-reflection-isarray-vs-instanceof ... the code you are showing is perfectly fine. So: what is your problem. – GhostCat May 30 '19 at 18:57
  • Nowhere in your code are you trying to iterate over anything. Can you please show the code that is generating that error? My hunch that is you're trying to iterate over `x` without casting it (just because the object being referred to by `x` is an array doesn't mean you can perform array operations on `x`, since the type of the *variable* is `Object`, not `Object[]`). – azurefrog May 30 '19 at 18:59
  • I apologize I just updated my code to show what I'm actually trying to do – Karim Shoorbajee May 30 '19 at 19:04

1 Answers1

5

Putting stuff inside a conditional with an instanceof doesn't magically let the compiler know the thing is an instance of that. You've actually got to cast:

if (x instanceof Object[]){
  for (Object item : (Object[]) x) {
  }
}
Andy Turner
  • 137,514
  • 11
  • 162
  • 243