Как узнать тип переменной java
Перейти к содержимому

Как узнать тип переменной java

  • автор:

Как узнать тип переменной java

Аватар пользователя Иван Полежаев

В Java можно узнать тип переменной, используя оператор instanceof . Он позволяет проверить, является ли объект экземпляром определенного класса.

В этом примере мы объявляем переменные str и integer , типы которых String и Integer соответственно. Затем мы используем оператор instanceof для проверки, являются ли эти переменные экземплярами классов String , Integer или Object .

Как видно из примера, переменная str является экземпляром класса String , а переменная integer — экземпляром класса Integer . Кроме того, обе переменные также являются экземплярами класса Object , так как все классы в Java наследуются от этого класса.

Как проверить тип переменной в Java?

Как я могу проверить, чтобы моя переменная была int, array, double и т.д.

Изменить: Например, как я могу проверить, что переменная является массивом? Есть ли какая-нибудь функция для этого?

11 ответов

Java — это статически типизированный язык, поэтому компилятор делает большую часть этой проверки для вас. Когда вы объявляете переменную определенным типом, компилятор будет гарантировать, что это только когда-либо назначенные значения этого типа (или значения, которые являются подтипами этого типа).

Приведенные вами примеры (int, array, double) — это все примитивы, а подтипов их нет. Таким образом, если вы объявляете переменную как int :

Вы можете быть уверены, что он будет удерживать только int значения.

Если вы указали переменную как List , однако, возможно, что переменная будет содержать подтипы List . К ним относятся: ArrayList , LinkedList и т.д.

Если у вас есть переменная List , и вам нужно знать, была ли она ArrayList , вы могли бы сделать следующее:

Однако, если вы считаете, что вам нужно это сделать, вы можете подумать о своем подходе. В большинстве случаев, если вы будете следовать объектно-ориентированным принципам, вам не нужно будет этого делать. Конечно, есть исключения для каждого правила.

Obtaining Field Types

A field may be either of primitive or reference type. There are eight primitive types: boolean , byte , short , int , long , char , float , and double . A reference type is anything that is a direct or indirect subclass of java.lang.Object including interfaces, arrays, and enumerated types.

The FieldSpy example prints the field's type and generic type given a fully-qualified binary class name and field name.

Sample output to retrieve the type of the three public fields in this class ( b , name , and the parameterized type list ), follows. User input is in italics.

Java typeof Operator

Java typeof Operator

This tutorial introduces how to get the data type of a variable or value in Java and lists some example codes to understand the topic.

In Java, to get type of a variable or a value, we can use getClass() method of Object class. This is the only way to do this, unlike JavaScript with the typeof() method to check type.

Please enable JavaScript

Since we used the getClass() method of Object class, it works with objects only, not primitives. If you want to get the type of primitives, then first convert them using the wrapper class. Let’s understand with some examples.

Get the Type of a Variable/Value in Java

In this example, we used getClass() to check the type of a variable. Since this variable is a string type, then we can directly call the method. See the example below.

Notice that the getClass() method returns a fully qualified class name, including a package name such as java.lang.String in our case.

Get the Type of Any Variable/Value in Java

In the above example, we used a string variable and got its type similarly; we can also use another type of variable, and the method returns the desired result. See the example below.

In this example, we created two more variables, integer and character, apart from string and used the getClass() method.

The getClass() method returns a complete qualified name of the class, including the package name. If you wish to get only the type name, you can use the getSimpleName() method that returns a single string. See the example below.

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *