0

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.

2 Answers 2

3

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?

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

3 Comments

This will not work like the instanceof operator if polymorphism is involved. For example, Class<?> cls = Numer.class; Object obj = new Integer(0); System.out.println(cls == obj.getClass()); will print false although obj instanceof Number.
Thanks for the help, but i have to create a Generic Class within the if Statement, and Something like new ArrayList<String> is Possible, but ArrayList<String.class> or ArrayList<classes[i]> doesn't work
@mac.1 Yes, this is downright impossible, I'm afraid, because of type erasure: generics lose all their type parameters during the compilation phase. This is another reason for thinking that you need to rework your code.
1

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.

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.