Heisenbug
Heisenbug

Reputation: 39164

How to establish the type of a class type in Java, without instantiated objects?

Suppose I have an array of class values in Java and I want to iterate through the array to find at which position is located a Double. I tried the following:

public class ClassTypes {

    public static void main(String[] args) {
        Class []types = {String.class, Double.class};
        for (int i = 0 ; i < types.length; i++)
        {
                if (types[i].isInstance(Double.class)){
                    System.out.println("DOUBLE"); //never printed 
                }
        }
    }}

I have no instance of an object so I can't use instanceof, and I would like to avoid the use of getName on class object to perform the comparison. Can anyone suggest me how to do it?

Upvotes: 0

Views: 93

Answers (2)

bestsss
bestsss

Reputation: 12056

What you actually need is Double.class.isAssignableFrom(types[i]), not equals and not == (they are the same for Class). For final classes like Double and String it doesn't matter of course.

If you have tried to check if the class is a java.lang.Number (or any interface/abstract class), the == approach would have failed.

Upvotes: 1

Oliver Charlesworth
Oliver Charlesworth

Reputation: 272467

types[i].equals(Double.class)?

Upvotes: 3

Related Questions