如何检查Java中的变量类型?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3993982/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-14 08:04:33  来源:igfitidea点击:

How to check type of variable in Java?

java

提问by Strawberry

How can I check to make sure my variable is an int, array, double, etc...?

如何检查以确保我的变量是 int、array、double 等...?

Edit: For example, how can I check that a variable is an array? Is there some function to do this?

编辑:例如,如何检查变量是否为数组?有什么功能可以做到这一点吗?

回答by Alex Abdugafarov

You may work with Integer instead of int, Double instead of double, etc. (such classes exists for all primitive types). Then you may use the operator instanceof, like if(var instanceof Integer){...}

您可以使用 Integer 代替 int、Double 代替 double 等(此类类适用于所有原始类型)。然后你可以使用操作符 instanceof,比如if(var instanceof Integer){...}

回答by pkaeding

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).

Java 是一种静态类型语言,因此编译器会为您完成大部分检查。一旦您将变量声明为某种类型,编译器将确保只为其分配该类型的值(或该类型的子类型的值)。

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, array, double) 这些都是基元,并且没有它们的子类型。因此,如果您将一个变量声明为一个int

int x;

You can be sure it will only ever hold intvalues.

您可以确定它只会保存int值。

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但是,如果您将变量声明为 a ,则该变量可能会包含 的子类型List。这些的实例包括ArrayListLinkedList

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

如果您确实有一个List变量,并且需要知道它是否为ArrayList,则可以执行以下操作:

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.

但是,如果您发现自己认为需要这样做,则可能需要重新考虑您的方法。在大多数情况下,如果您遵循面向对象的原则,则不需要这样做。当然,每条规则都有例外。

回答by user207421

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.

关于第二部分,您不知道变量是否是数组的唯一情况是它是否是对象。在哪种情况下object.getClass().isArray()会告诉你。

回答by Mvcoile

Actually quite easy to roll your own tester, by abusing Java's method overload ability. Though I'm still curious if there is an official method in the sdk.

通过滥用 Java 的方法重载能力,实际上很容易推出自己的测试仪。虽然我仍然很好奇 sdk 中是否有官方方法。

Example:

例子:

class Typetester {
    void printType(byte x) {
        System.out.println(x + " is an byte");
    }
    void printType(int x) {
        System.out.println(x + " is an int");
    }
    void printType(float x) {
        System.out.println(x + " is an float");
    }
    void printType(double x) {
        System.out.println(x + " is an double");
    }
    void printType(char x) {
        System.out.println(x + " is an char");
    }
}

then:

然后:

Typetester t = new Typetester();
t.printType( yourVariable );

回答by Glen Pierce

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

a.getClass().getName()- 将为您提供由 引用的实际对象a的数据类型,但不会提供变量a最初声明为或随后转换为的数据类型。

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

boolean b = a instanceof String- 将告诉您所引用的实际对象是否a是特定类的实例。同样,变量a最初声明为或随后强制转换为的数据类型与 instanceof 运算符的结果无关。

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

我从以下信息中获取了这些信息: 您如何知道 Java 中的变量类型?

This can happen. I'm trying to parse a Stringinto 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.

这可能发生。我正在尝试将 a 解析String为 int,Integer.parseInt(s.substring(a, b))在尝试总结之前,我想知道我是踢出 int 还是垃圾。

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

顺便说一下,这被称为反射。以下是有关该主题的更多信息:http: //docs.oracle.com/javase/tutorial/reflect/

回答by Vinicius Arruda

I did it using: if(x.getClass() == MyClass.class){...}

我是用的: if(x.getClass() == MyClass.class){...}

回答by Dev

public class Demo1 {

公共类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());

}

}

}

回答by Amogh

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.

PS 是的,我知道这也不会检查原语。

回答by Neil Regan

I wasn't happy with any of these answers, and the one that's right has no explanation and negative votes so I searched around, found some stuff and edited it so that it is easy to understand. Have a play with it, not as straight forward as one would hope.

我对这些答案中的任何一个都不满意,正确的答案没有任何解释和反对票,所以我四处搜索,找到了一些东西并对其进行了编辑,以便于理解。玩玩它,而不是像人们希望的那样直接。

//move your variable into an Object type
Object obj=whatYouAreChecking;
System.out.println(obj);

// moving the class type into a Class variable
Class cls=obj.getClass();
System.out.println(cls);

// convert that Class Variable to a neat String
String answer = cls.getSimpleName();
System.out.println(answer);

Here is a method:

这是一个方法:

public static void checkClass (Object obj) {
    Class cls = obj.getClass();
    System.out.println("The type of the object is: " + cls.getSimpleName());       
}

回答by Debayan

Just use:

只需使用:

.getClass().getSimpleName();

Example:

例子:

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

Output:

输出:

StringBuilder