- Как проверить тип объекта java
- Получить тип объекта в Java
- Получить тип объекта с помощью getClass() в Java
- Получить тип объекта с помощью instanceOf в Java
- Получить тип объекта класса, созданного вручную в Java
- Сопутствующая статья — Java Object
- Как проверить тип объекта java
- Check Type of a Variable in Java
- Use getClass().getSimpleName() to Check the Type of a Variable in Java
- Related Article — Java Data Type
- Java typeof Operator
- Get the Type of a Variable/Value in Java
- Get the Type of Any Variable/Value in Java
- Related Article — Java Operator
Как проверить тип объекта java
В Java можно узнать тип переменной, используя оператор instanceof . Он позволяет проверить, является ли объект экземпляром определенного класса.
public class Main public static void main(String[] args) String str = "Hello, Hexlet!"; Integer integer = 123; System.out.println(str instanceof String); // => true System.out.println(integer instanceof Integer); // => true System.out.println(str instanceof Object); // => true System.out.println(integer instanceof Object); // => true > >
В этом примере мы объявляем переменные str и integer , типы которых String и Integer соответственно. Затем мы используем оператор instanceof для проверки, являются ли эти переменные экземплярами классов String , Integer или Object .
Как видно из примера, переменная str является экземпляром класса String , а переменная integer — экземпляром класса Integer . Кроме того, обе переменные также являются экземплярами класса Object , так как все классы в Java наследуются от этого класса.
Получить тип объекта в Java
- Получить тип объекта с помощью getClass() в Java
- Получить тип объекта с помощью instanceOf в Java
- Получить тип объекта класса, созданного вручную в Java
В этой статье мы узнаем, как получить тип объекта в Java. Если объект поступает из источника, полезно проверить тип объекта. Это место, где мы не можем проверить тип объектов, например из API или частного класса, к которому у нас нет доступа.
Получить тип объекта с помощью getClass() в Java
В первом методе мы проверяем тип Object классов-оболочек, таких как Integer и String . У нас есть два объекта, var1 и var2 , для проверки типа. Мы воспользуемся методом getClass() класса Object , родительского класса всех объектов в Java.
Проверяем класс по условию если . Поскольку классы-оболочки также содержат класс поля, возвращающий тип, мы можем проверить, чей тип совпадает с var1 и var2 . Ниже мы проверяем оба объекта трех типов.
public class ObjectType public static void main(String[] args) Object var1 = Integer.valueOf("15"); Object var2 = String.valueOf(var1); if (var1.getClass() == Integer.class) System.out.println("var1 is an Integer"); > else if (var1.getClass() == String.class) System.out.println("var1 is a String"); > else if (var1.getClass() == Double.class) System.out.println("var1 is a Double"); > if (var2.getClass() == Integer.class) System.out.println("var2 is an Integer"); > else if (var2.getClass() == String.class) System.out.println("var2 is a String"); > else if (var2.getClass() == Double.class) System.out.println("var2 is a Double"); > > >
var1 is an Integer var2 is a String
Получить тип объекта с помощью instanceOf в Java
Другой способ получить тип объекта в Java — использовать функцию instanceOf ; он возвращается, если экземпляр объекта совпадает с заданным классом. В этом примере у нас есть объекты var1 и var2 , которые проверяются с этими тремя типами: Integer , String и Double ; если какое-либо из условий выполняется, мы можем выполнить другой код.
Поскольку var1 имеет тип Integer , условие var1 instanceOf Integer станет истинным, а var2 — Double , так что var2 instanceOf Double станет истинным.
public class ObjectType public static void main(String[] args) Object var1 = Integer.valueOf("15"); Object var2 = Double.valueOf("10"); if (var1 instanceof Integer) System.out.println("var1 is an Integer"); > else if (var1 instanceof String) System.out.println("var1 is a String"); > else if (var1 instanceof Double) System.out.println("var1 is a Double"); > if (var2 instanceof Integer) System.out.println("var2 is an Integer"); > else if (var2 instanceof String) System.out.println("var2 is a String"); > else if (var2 instanceof Double) System.out.println("var2 is a Double"); > > >
var1 is an Integer var2 is a Double
Получить тип объекта класса, созданного вручную в Java
Мы проверили типы классов-оболочек, но в этом примере мы получаем тип трех объектов трех созданных вручную классов. Мы создаем три класса: ObjectType2 , ObjectType3 и ObjectType4 .
ObjectType3 наследует ObjectType4, а ObjectType2 наследует ObjectType3. Теперь мы хотим узнать тип объектов всех этих классов. У нас есть три объекта: obj , obj2 и obj3 ; мы используем оба метода, которые мы обсуждали в приведенных выше примерах: getClass () и instanceOf.
Однако есть отличия между типом obj2 . Переменная obj2 вернула тип ObjectType4 , а ее класс — ObjectType3 . Это происходит потому, что мы наследуем класс ObjectType4 в ObjectType3 , а instanceOf проверяет все классы и подклассы. obj вернул ObjectType3 , потому что функция getClass() проверяет только прямой класс.
public class ObjectType public static void main(String[] args) Object obj = new ObjectType2(); Object obj2 = new ObjectType3(); Object obj3 = new ObjectType4(); if (obj.getClass() == ObjectType4.class) System.out.println("obj is of type ObjectType4"); > else if (obj.getClass() == ObjectType3.class) System.out.println("obj is of type ObjectType3"); > else if (obj.getClass() == ObjectType2.class) System.out.println("obj is of type ObjectType2"); > if (obj2 instanceof ObjectType4) System.out.println("obj2 is an instance of ObjectType4"); > else if (obj2 instanceof ObjectType3) System.out.println("obj2 is an instance of ObjectType3"); > else if (obj2 instanceof ObjectType2) System.out.println("obj2 is an instance of ObjectType2"); > if (obj3 instanceof ObjectType4) System.out.println("obj3 is an instance of ObjectType4"); > else if (obj3 instanceof ObjectType3) System.out.println("obj3 is an instance of ObjectType3"); > else if (obj3 instanceof ObjectType2) System.out.println("obj3 is an instance of ObjectType2"); > > > class ObjectType2 extends ObjectType3 int getAValue3() System.out.println(getAValue2()); a = 300; return a; > > class ObjectType3 extends ObjectType4 int getAValue2() System.out.println(getAValue1()); a = 200; return a; > > class ObjectType4 int a = 50; int getAValue1() a = 100; return a; > >
obj is of type ObjectType2 obj2 is an instance of ObjectType4 obj3 is an instance of ObjectType4
Rupam Saini is an android developer, who also works sometimes as a web developer., He likes to read books and write about various things.
Сопутствующая статья — Java Object
Как проверить тип объекта java
В Java можно узнать тип переменной, используя оператор instanceof . Он позволяет проверить, является ли объект экземпляром определенного класса.
public class Main public static void main(String[] args) String str = "Hello, Hexlet!"; Integer integer = 123; System.out.println(str instanceof String); // => true System.out.println(integer instanceof Integer); // => true System.out.println(str instanceof Object); // => true System.out.println(integer instanceof Object); // => true > >
В этом примере мы объявляем переменные 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 .
public class MyClass public static void main(String args[]) String str = "Sample String"; System.out.println(str.getClass().getSimpleName()); > >
The below example illustrates the use of this method on an array.
public class MyClass public static void main(String args[]) String[] arr = new String[5]; System.out.println(arr.getClass().getSimpleName()); > >
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.
public class MyClass public static void main(String args[]) int x = 5; System.out.println(((Object)x).getClass().getSimpleName()); > >
Related Article — Java Data Type
Java typeof Operator
- Get the Type of a Variable/Value in Java
- Get the Type of Any Variable/Value in Java
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.
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.
public class SimpleTesting public static void main(String[] args) String msg = "Hello"; System.out.println(msg); System.out.println("Type is: "+msg.getClass()); > >
Hello Type is: class java.lang.String
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.
package javaexample; public class SimpleTesting public static void main(String[] args) String msg = "Hello"; System.out.println(msg); System.out.println("Type is: "+msg.getClass()); // Integer Integer val = 20; System.out.println(val); System.out.println("Type is: "+val.getClass()); // Character Character ch = 'G'; System.out.println(ch); System.out.println("Type is: "+ch.getClass()); > >
Hello Type is: class java.lang.String 20 Type is: class java.lang.Integer G Type is: class java.lang.Character
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.
package javaexample; public class SimpleTesting public static void main(String[] args) String msg = "Hello"; System.out.println(msg); System.out.println("Type is: "+msg.getClass().getSimpleName()); // Integer Integer val = 20; System.out.println(val); System.out.println("Type is: "+val.getClass().getSimpleName()); // Character Character ch = 'G'; System.out.println(ch); System.out.println("Type is: "+ch.getClass().getSimpleName()); > >
Hello Type is: String 20 Type is: Integer G Type is: Character