How to check type of variable in Java?

前端 未结 14 1647
别跟我提以往
别跟我提以往 2020-11-28 05:14

How can I check to make sure my variable is an int, array, double, etc...?

Edit: For example, how can I check that a variable is an array? Is there some function to

14条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-11-28 06:00

    I wasn't happy with any of these answers, and the one that's right has no explanation and negative votes so I searched around, found some stuff and edited it so that it is easy to understand. Have a play with it, not as straight forward as one would hope.

    //move your variable into an Object type
    Object obj=whatYouAreChecking;
    System.out.println(obj);
    
    // moving the class type into a Class variable
    Class cls=obj.getClass();
    System.out.println(cls);
    
    // convert that Class Variable to a neat String
    String answer = cls.getSimpleName();
    System.out.println(answer);
    

    Here is a method:

    public static void checkClass (Object obj) {
        Class cls = obj.getClass();
        System.out.println("The type of the object is: " + cls.getSimpleName());       
    }
    

提交回复
热议问题