Как проверить тип переменной в Java?
Как я могу проверить, чтобы моя переменная была int, array, double и т.д.
Изменить: Например, как я могу проверить, что переменная является массивом? Есть ли какая-нибудь функция для этого?
11 ответов
Java — это статически типизированный язык, поэтому компилятор делает большую часть этой проверки для вас. Когда вы объявляете переменную определенным типом, компилятор будет гарантировать, что это только когда-либо назначенные значения этого типа (или значения, которые являются подтипами этого типа).
Приведенные вами примеры (int, array, double) — это все примитивы, а подтипов их нет. Таким образом, если вы объявляете переменную как int :
Вы можете быть уверены, что он будет удерживать только int значения.
Если вы указали переменную как List , однако, возможно, что переменная будет содержать подтипы List . К ним относятся: ArrayList , LinkedList и т.д.
Если у вас есть переменная List , и вам нужно знать, была ли она ArrayList , вы могли бы сделать следующее:
Однако, если вы считаете, что вам нужно это сделать, вы можете подумать о своем подходе. В большинстве случаев, если вы будете следовать объектно-ориентированным принципам, вам не нужно будет этого делать. Конечно, есть исключения для каждого правила.
Как узнать тип переменной java
В Java можно узнать тип переменной, используя оператор instanceof . Он позволяет проверить, является ли объект экземпляром определенного класса.
В этом примере мы объявляем переменные str и integer , типы которых String и Integer соответственно. Затем мы используем оператор instanceof для проверки, являются ли эти переменные экземплярами классов String , Integer или Object .
Как видно из примера, переменная str является экземпляром класса String , а переменная integer — экземпляром класса Integer . Кроме того, обе переменные также являются экземплярами класса Object , так как все классы в Java наследуются от этого класса.
Check Type of a Variable in Java
This tutorial discusses the method to check the type of a variable in Java.
Use getClass().getSimpleName() to Check the Type of a Variable in Java
We can check the type of a variable in Java by calling getClass().getSimpleName() method via the variable. The below example illustrates the use of this function on non-primitive data types like String .
The below example illustrates the use of this method on an array.
This method is callable by objects only; therefore, to check the type of primitive data types, we need to cast the primitive to Object first. The below example illustrates how to use this function to check the type of non-primitive data types.
How do you know a variable type in java? [duplicate]
And I want to know what type it is, i.e., the output should be java.lang.String How do I do this?
7 Answers 7
Expanding on Martin’s answer.
Martins Solution
Expanded Solution
If you want it to work with anything you can do this:
In case of a primitive type, it will be wrapped (Autoboxed) in a corresponding Object variant.
Example #1 (Regular)
Example #2 (Generics)
Additional Learning
- Material on Java Types, Values and Variables: https://docs.oracle.com/javase/specs/jls/se7/html/jls-4.html
- Autoboxing and Unboxing: https://docs.oracle.com/javase/tutorial/java/data/autoboxing.html
- Docs on Pattern Matching for instanceof: https://docs.oracle.com/en/java/javase/14/language/pattern-matching-instanceof-operator.html
If you want the name, use Martin’s method. If you want to know whether it’s an instance of a certain class:
boolean b = a instanceof String
I learned from the Search Engine(My English is very bad , So code. ) How to get variable’s type? Up’s :
Use operator overloading feature of java
I think we have multiple solutions here:
- instance of could be a solution.
Why? In Java every class is inherited from the Object class itself. So if you have a variable and you would like to know its type. You can use
- System.out.println(((Object)f).getClass().getName());
- Integer.class.isInstance(1985); // gives true
I agree with what Joachim Sauer said, not possible to know (the variable type! not value type!) unless your variable is a class attribute (and you would have to retrieve class fields, get the right field by name. )
Actually for me it’s totally impossible that any a.xxx().yyy() method give you the right answer since the answer would be different on the exact same object, according to the context in which you call this method.
As teehoo said, if you know at compile a defined list of types to test you can use instanceof but you will also get subclasses returning true.