mac.1
mac.1

Reputation: 100

Java Object itself in array

I want so save "Object" inside an array. I DONT want to save "new Object()" inside an array.

Why? I have 3 big If Statements where i check if a Instance is instanceof SomeClass, e.g.

if (x instanceof String) {
   SomeMethod(x, String);
}

I Plan Something like:

Class<?>[] classes = {Object, String, SomeOtherClass};
for (int i = 0; i < 3; i++) {
    if (x instanceof classes [i]) {
       SomeMethod(x, classes [i]);
    }
}

However this is working

Class<?>[] classes = {Object.class, String.class, SomeOtherClass.class};

but then i can't use instanceof any more.

Any Suggestions?

P.S: while searching for this i only found how to save an Instance of a Class inside an array, not the Class itself...

Edit: at the Position of SomeMethod i want to use a generic Type based on the Class (Object,String). This does not work with Object.class, String.class.

Upvotes: 0

Views: 116

Answers (2)

5gon12eder
5gon12eder

Reputation: 25419

You cannot store “Object” inside an array because Object is not a thing. The string Object is a class name and meaningful to the compiler but nothing you can operate on in your program which (apart from the built-in primitives) can only deal with instances of classes, that is objects. Object.class, on the other hand, is an object (of type Class).

What you are looking for is java.lang.Class.isInstance. Then use a list of Class objects.

Upvotes: 1

chiastic-security
chiastic-security

Reputation: 20520

Use

if (x.getClass() == classes[i]) {

instead of instanceof for this.

But please be aware that any code that uses either of these techniques is suspicious from the start and probably needs refactoring. Why do you want to store your objects in such a way that you don't know their type?

Upvotes: 3

Related Questions