wassup
wassup

Reputation: 2503

How do I check if a given object is an instance of certain class when in Object[] array?

I was trying to find out how to determine which class a given object instantiate when it's in Object[] array. For example:

Object[] array = new Object[]{175, "sss", new Table(), true};
Object obj = array[0]; // hmm... can this be used as an integer or maybe as a string?

Is it even possible?

Upvotes: 1

Views: 3450

Answers (3)

oxbow_lakes
oxbow_lakes

Reputation: 134270

You can test whether it is an instance of a pre-known class (and cast it) like this:

if (obj instanceof String) {
  String s = (String) obj; //casts the obj now you know it's a String
}

I like to think of this not as making any changes to the object but just as revealing its true character. For example, it's a bit like seeing a person and not knowing what language they speak - the person is still French, or Italian, just that you don't know which yet. The cast (i.e. (String) obj) is you telling the compiler the equivalent of "I know this person speaks French"

Or you can gets its class like this:

Class<?> clazz = obj.getClass();

A Class instance can be used to make the same check:

String.class.isInstance(obj) {
  String s = String.class.cast(obj);
}

Upvotes: 2

stryba
stryba

Reputation: 2027

You can try using instanceof or you can try getClass().isAssignableFrom(), whatever fits your needs

Upvotes: 4

Jon Skeet
Jon Skeet

Reputation: 1500675

You can call getClass() to find out the class of a particular object, or you can use instanceof to check a specific type:

if (array[0] instanceof Integer) {
}

Normally having to do a lot of this indicates a weakness in your design though - you should try to avoid needing to do this.

Upvotes: 11

Related Questions