How to check type of variable in Java?

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

    I hit this question as I was trying to get something similar working using Generics. Taking some of the answers and adding getClass().isArray() I get the following that seems to work.

    public class TypeTester {
    
     String tester(T ToTest){
    
        if (ToTest instanceof Integer) return ("Integer");
        else if(ToTest instanceof Double) return ("Double");
        else if(ToTest instanceof Float) return ("Float");
        else if(ToTest instanceof String) return ("String");
        else if(ToTest.getClass().isArray()) return ("Array");
        else return ("Unsure");
    }
    }
    

    I call it with this where the myArray part was simply to get an Array into callFunction.tester() to test it.

    public class Generics {
    public static void main(String[] args) {
        int [] myArray = new int [10];
    
        TypeTester callFunction = new TypeTester();
        System.out.println(callFunction.tester(myArray));
    }
    }
    

    You can swap out the myArray in the final line for say 10.2F to test Float etc

提交回复
热议问题