How to check type of variable in Java?

前端 未结 14 1528
别跟我提以往
别跟我提以往 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 <T extends Number>{
    
    <T extends Object> 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<Integer> callFunction = new TypeTester<Integer>();
        System.out.println(callFunction.tester(myArray));
    }
    }
    

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

    0 讨论(0)
  • 2020-11-28 05:48

    a.getClass().getName() - will give you the datatype of the actual object referred to by a, but not the datatype that the variable a was originally declared as or subsequently cast to.

    boolean b = a instanceof String - will give you whether or not the actual object referred to by a is an instance of a specific class. Again, the datatype that the variable a was originally declared as or subsequently cast to has no bearing on the result of the instanceof operator.

    I took this information from: How do you know a variable type in java?

    This can happen. I'm trying to parse a String into an int and I'd like to know if my Integer.parseInt(s.substring(a, b)) is kicking out an int or garbage before I try to sum it up.

    By the way, this is known as Reflection. Here's some more information on the subject: http://docs.oracle.com/javase/tutorial/reflect/

    0 讨论(0)
  • 2020-11-28 05:49

    Just use:

    .getClass().getSimpleName();
    

    Example:

    StringBuilder randSB = new StringBuilder("just a String");
    System.out.println(randSB.getClass().getSimpleName());
    

    Output:

    StringBuilder
    
    0 讨论(0)
  • 2020-11-28 05:51

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

    public <T extends Object> 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.

    0 讨论(0)
  • 2020-11-28 05:56

    public class Demo1 {

    Object printType(Object o)
    {
        return o;
    }
     public static void main(String[] args) {
    
        Demo1 d=new Demo1();
        Object o1=d.printType('C');
        System.out.println(o1.getClass().getSimpleName());
    
    }
    

    }

    0 讨论(0)
  • 2020-11-28 05:58

    Java is a statically typed language, so the compiler does most of this checking for you. Once you declare a variable to be a certain type, the compiler will ensure that it is only ever assigned values of that type (or values that are sub-types of that type).

    The examples you gave (int, array, double) these are all primitives, and there are no sub-types of them. Thus, if you declare a variable to be an int:

    int x;
    

    You can be sure it will only ever hold int values.

    If you declared a variable to be a List, however, it is possible that the variable will hold sub-types of List. Examples of these include ArrayList, LinkedList, etc.

    If you did have a List variable, and you needed to know if it was an ArrayList, you could do the following:

    List y;
    ...
    if (y instanceof ArrayList) { 
      ...its and ArrayList...
    }
    

    However, if you find yourself thinking you need to do that, you may want to rethink your approach. In most cases, if you follow object-oriented principles, you will not need to do this. There are, of course, exceptions to every rule, though.

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