如何检查Java中的变量类型? [英] How to check type of variable in Java?
问题描述
我如何检查以确保我的变量是int,array,double等......?
How can I check to make sure my variable is an int, array, double, etc...?
编辑:例如,如何检查变量是否为数组?是否有一些函数可以执行此操作?
For example, how can I check that a variable is an array? Is there some function to do this?
推荐答案
Java是一种静态类型语言,因此编译器会为您进行大部分检查。一旦将变量声明为某种类型,编译器将确保只为该类型赋值(或者是该类型的子类型的值)。
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).
您给出的示例(int,array,double)这些都是基元,并且没有它们的子类型。因此,如果您将变量声明为 int
:
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;
您可以确定它只会持有 int
values。
You can be sure it will only ever hold int
values.
但是,如果您将变量声明为 List
,则变量可能是将保存 List
的子类型。这些示例包括 ArrayList
, LinkedList
等。
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.
如果你确实有 List
变量,并且你需要知道它是否是 ArrayList
,你可以这样做以下:
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 re-think your approach. In most cases, if you follow object-oriented principals, you will not need to do this. There are, of course, exceptions to every rule, though.
这篇关于如何检查Java中的变量类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!