How to check type of variable in Java?

前端 未结 14 1510
别跟我提以往
别跟我提以往 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());       
    }
    
    0 讨论(0)
  • 2020-11-28 06:01

    I did it using: if(x.getClass() == MyClass.class){...}

    0 讨论(0)
  • 2020-11-28 06:03

    You can check it easily using Java.lang.Class.getSimpleName() Method Only if variable has non-primitive type. It doesnt work with primitive types int ,long etc.

    reference - Here is the Oracle docs link

    0 讨论(0)
  • 2020-11-28 06:04

    Actually quite easy to roll your own tester, by abusing Java's method overload ability. Though I'm still curious if there is an official method in the sdk.

    Example:

    class Typetester {
        void printType(byte x) {
            System.out.println(x + " is an byte");
        }
        void printType(int x) {
            System.out.println(x + " is an int");
        }
        void printType(float x) {
            System.out.println(x + " is an float");
        }
        void printType(double x) {
            System.out.println(x + " is an double");
        }
        void printType(char x) {
            System.out.println(x + " is an char");
        }
    }
    

    then:

    Typetester t = new Typetester();
    t.printType( yourVariable );
    
    0 讨论(0)
  • 2020-11-28 06:04

    Basically , For example :

    public class Kerem
    {
        public static void main(String[] args)
        {
            short x = 10;
            short y = 3;
            Object o = y;
            System.out.println(o.getClass()); // java.lang.Short
        }
    
    }
    
    0 讨论(0)
  • 2020-11-28 06:08

    You may work with Integer instead of int, Double instead of double, etc. (such classes exists for all primitive types). Then you may use the operator instanceof, like if(var instanceof Integer){...}

    0 讨论(0)
提交回复
热议问题