Java узнать тип объекта

Как узнать тип переменной 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

Получить тип объекта в Java

  1. Получить тип объекта с помощью getClass() в Java
  2. Получить тип объекта с помощью instanceOf в Java
  3. Получить тип объекта класса, созданного вручную в 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

Источник

How to Get Type of Object in Java?

An object is a physical entity that has its own state and behavior, and it acts as a unique instance of a Java class. It. When the object originates from a source, it is considered useful to examine the object type. Also, knowing the type of an object is crucial when working with a collection that includes different objects or when it is required to execute the logical operation with the same kind of variables.

This article will help you to learn the method to get the type of an object in Java.

How to Get Type of Object in Java?

For getting the type of predefined or user-defined class object in Java, you can use:

We will now check out each of the mentioned methods one by one!

Method 1: Get Type of Pre-defined Class Object Using getClass() Method

In Java, we have predefined classes like wrapper classes such as String, Double, Integer, and many more. Sometimes we need to verify the object type while using predefined classes. For this purpose, Java offers a “getClass()” method that belongs to the “Object” class.

Syntax
The syntax of the “getClass()” method is given as follows:

Here, the “getClass()” method will return the class of the specified “x” object.

Example
In this example, we will create a String type object named “x” containing the following value:

Next, we will print a statement using the “System.out.println()” method:

Lastly, we will get the type of the object “x” by calling the “getClass()” method:

The output shows that the created variable belongs to the Java String class:

Let’s see another method to get the object type using the “instanceof” operator.

Method 2: Get Type of Pre-defined Class Object Using “instanceof” Operator

You can also utilize the “instanceof” operator to check the object type in a Java program. This operator returns a boolean value which indicates whether the object is an instance of the particular class or not.

Syntax
The syntax of the “instanceof” is as follows:

Here, “x” is an object and “Integer” is the predefined Java wrapper class. The “instanceof” operator checks whether the object belongs to the mentioned class or not and returns a boolean value.

Example
In this example, we have an object “x” of the Integer class having “5” as its value:

Next, we will print a statement using the “System.out.println()” method:

Now, we will check whether the object is an instance of an Integer class or not:

The output displayed “true” as the object “x” is an instance of the Integer class:

At this point, you may be wondering about how to get the type of user-defined class object. The below-given section will assist you in this regard.

Method 3: Get Type of User-defined Class Object Using getClass() Method

You can also get the type of the user-defined class object with the help of the “getClass()” method. In such a scenario, we will compare the object with the class name using the “==” comparison operator.

Syntax
For the specified purpose, the syntax of “getClass()” method is given as:

Here, the “getClass()” method is called by the “myclassObj” object of the “MyClass” and then compared with the name using the comparison operator “==”.

Example
In this example, we have three classes named “MyClass”, “MynewClass”, and “Example”, where MyClass acts as a parent class of MynewClass:

The “MynewClass” is a child class as it is extended from “MyClass”:

In the main() method of the class “Example”, we will declare and instantiate an object of the parent class “MyClass”. Then check whether the created object belongs to which class; parent or child? To do so, we will call the “getClass()” method with the created object and compare the resultant value with parent and child class names using if-else-if conditions:

public class Example {
public static void main ( String [ ] args ) {
MyClass myclassObj = new MyClass ( ) ;
if ( myclassObj. getClass ( ) == MyClass. class ) {
System . out . println ( «The object ‘myclassObj’ is a type of ‘MyClass'» ) ;
} else if ( myclassObj. getClass ( ) == MynewClass. class ) {
System . out . println ( «The object ‘myclassObj’ is a type of ‘MynewClass'» ) ;
}
}
}

The output indicates that the object “myclassObj” belongs to the parent class named “MyClass”:

Now, head toward the next section!

Method 4: Get Type of User-defined Class Object Using “instanceof” Operator

Similar to predefined classes, for user-defined classes, you can also get the type of object by using the “instanceof” operator.

Syntax
The syntax is given below:

Here, the “instanceof” operator will check if the “myclassObj” is an instance of “MyClass” or not.

Example
We will now utilize the same classes which we have created in the previously mentioned example. The only difference is that we will use the “instanceof” operator to verify if the created object instance belongs to the parent or child class:

public class Example {
public static void main ( String [ ] args ) {
MyClass myclassObj = new MyClass ( ) ;
if ( myclassObj instanceof MyClass ) {
System . out . println ( «The object ‘myclassObj’ is an instance of ‘MyClass'» ) ;
} else if ( myclassObj instanceof MynewClass ) {
System . out . println ( «The object ‘myclassObj’ is an instance of ‘MynewClass'» ) ;
}
}
}

The given output shows that the “instanceof” operator validated the type of the object as “MyClass”:

We have compiled all methods related to getting object type in Java.

Conclusion

To get a type of object in Java, you can use the “getClass()” method or the “instanceof” operator. These methods can be used to check object types for both predefined and user-defined classes. The getClass() method returns the class name while the “instanceof” operator returns a boolean value, where “true” indicates the object belongs to that specified class; otherwise, it returns “false”. This article provided all the methods to get the object type in Java.

About the author

Farah Batool

I completed my master’s degree in computer science. I am an academic researcher and love to learn and write about new technologies. I am passionate about writing and sharing my experience with the world.

Источник

Читайте также:  Javascript событие метрика примеры
Оцените статью