1

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?

2
  • Why are you storing everything in an Object array? Commented Feb 26, 2012 at 18:38
  • I use an Object array to store parameters for calling Lua functions. Commented Feb 26, 2012 at 18:39

3 Answers 3

11

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.

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

3 Comments

Specifically it may be no Integer but int
He has an array of Object, so you are sure there are no int
@MichalBorek instanceof works only on objects and int is not an object. If you asign int to Object, it will be automatically converted to Integer.
4

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

Comments

2

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);
}

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.