Hi All. I’m still relatively new to Java, so I landed up in a scenario where I thought my object was a Vector, but it was actually a String Object.

This cost me some time as I was trying to pass the Scoped Variable into one of my existing Vector Objects. I had checks to see if the Scoped Variable was null or blank, but I needed a check to see if it was in fact a Vector or just a String.

It’s the old problem of if you only have 1 value, then it’s a String, and when you start having more than 1, it’s an Array.

So in Java, when faced with this problem, you can use the .getClass() and .getName() method to check what you actually have.

The example below shows how I used this. I’m sure there’s a much better ways of doing this check, but for now, it works.

Cheers all.

 

EXAMPLE:

Vector myarray = new Vector();

if (viewScope.get(“ScopeName”).getClass().getName().equals(“java.lang.String”))

     //It’s a String value, not an Array

     myarray.add(viewScope.get(“ScopeName”).toString());

} else {

     //It’s an Array. Yippee!!

     myarray = (Vector) viewScope.get(“ScopeName”);

}

UPDATE NOTE:

Thanks to Tommy Valand, below is another example of how to achieve this (See Red Text below). It’s also noted that the below method is preferred to what I show above.

Thanks Tommy for your feedback.

 

Vector myarray = new Vector();

if (viewScope.get(“ScopeName”) instanceof String)

     //It’s a String value, not an Array

     myarray.add(viewScope.get(“ScopeName”).toString());

} else {

     //It’s an Array. Yippee!!

     myarray = (Vector) viewScope.get(“ScopeName”);

}