How to check type of variable in Java?

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

    The first part of your question is meaningless. There is no circumstance in which you don't know the type of a primitive variable at compile time.

    Re the second part, the only circumstance that you don't already know whether a variable is an array is if it is an Object. In which case object.getClass().isArray() will tell you.

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

    None of these answers work if the variable is an uninitialized generic type

    And from what I can find, it's only possible using an extremely ugly workaround, or by passing in an initialized parameter to your function, making it in-place, see here:

    <T> T MyMethod(...){ if(T.class == MyClass.class){...}}
    

    Is NOT valid because you cannot pull the type out of the T parameter directly, since it is erased at runtime time.

    <T> void MyMethod(T out, ...){ if(out.getClass() == MyClass.class){...}}
    

    This works because the caller is responsible to instantiating the variable out before calling. This will still throw an exception if out is null when called, but compared to the linked solution, this is by far the easiest way to do this

    I know this is a kind of specific application, but since this is the first result on google for finding the type of a variable with java (and given that T is a kind of variable), I feel it should be included

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