How to check type of variable in Java?

前端 未结 14 1611
别跟我提以往
别跟我提以往 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 05:51

    Well, I think checking the type of variable can be done this way.

    public  void checkType(T object) {    
        if (object instanceof Integer)
            System.out.println("Integer ");
        else if(object instanceof Double)
            System.out.println("Double ");
        else if(object instanceof Float)
            System.out.println("Float : ");
        else if(object instanceof List)
            System.out.println("List! ");
        else if(object instanceof Set)
            System.out.println("Set! ");
    }
    

    This way you need not have multiple overloaded methods. I think it is good practice to use collections over arrays due to the added benefits. Having said that, I do not know how to check for an array type. Maybe someone can improve this solution. Hope this helps!

    P.S Yes, I know that this doesn't check for primitives as well.

提交回复
热议问题