Win a copy of Think Java: How to Think Like a Computer Scientist this week in the Java in General forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

what syntax for getting instanceof an array?

 
Chris Jones
Greenhorn
Posts: 12
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I want to write a conditional expression that checks if an object is an array. Can I use instanceof for this? How is the syntax? I imagine something along these lines:

// code fragment:



but eh ... that's evidently not how things are, so what do I instead need to do to determine type of an array object?

all help much appreciated!
 
Ernest Friedman-Hill
author and iconoclast
Marshal
Pie
Posts: 24211
35
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Actually, your code snippet is fine (given that it appears inside a method, of course.) That's exactly the right thing to do. Maybe whatever you actually tried was a little bit different from this?
 
qingwu wang
Ranch Hand
Posts: 147
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I don't think it is a good way to solve your question. only as a referrence.
try{
String str = someArray.getClass().getName();
if(str!=null){
if(str.index("[")==0){
System.out.println("This is an array");
}
}
}catch(e){
}
 
Joanne Neal
Rancher
Posts: 3742
16
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Chris Jones:




If you're not worried about what type of array it is you could do
 
Jesper de Jong
Java Cowboy
Saloon Keeper
Posts: 15272
37
Android IntelliJ IDE Java Scala Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You can try something different, as qingwu and Joanne show, but still: the syntax you are trying to use is correct and should work. Have a good look at your source code again. Isn't there something else you overlooked? Maybe a missing brace or semi-colon?

Try copying and pasting this example, and compiling it: it works without errors.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic