How to check type of variable in Java?

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

提交回复
热议问题