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?
types[i].equals(Double.class)
?
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.
精彩评论