Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check whether an Object is String or String Array in java?

Tags:

java

A method is returning a Object or Object[] of type String but if I am casting with String[], it is giving class cast exception when it contains single string. How can i resolve this?

Is there any way to check whether it contains String or String[]?

like image 849
Shashank T Avatar asked Nov 22 '10 09:11

Shashank T


1 Answers

Sure, use the instanceof operator:

if (x instanceof String) {
  ...
}

if (x instanceof String[]) {
  ...
}

etc. It's not ideal to have to do this, mind you... is there any way you could redesign your API to avoid this?

like image 62
Jon Skeet Avatar answered Oct 15 '22 23:10

Jon Skeet