12

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[]?

2 Answers 2

26

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?

Sign up to request clarification or add additional context in comments.

2 Comments

Due to object orientation concerns. The very fact of using instanceof is equivalent, in this case, to saying "my method could have returned String[] in all cases (as a String can always be put in a String[1]), but as I was not smart enough to do it, i prefered to return anything and let you cope with it."
The easiest way to change the API is to always return a String[], with in stead of the String a String[] of size 1.
7

Rewrite the method to always return String[], even when there's only a single one.

Better yet, have it return List<String> and use Collections.singletonList() for the single-element case.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.