Get system type in java

How to determine Type of object at runtime in Java — Runtime Type Identification Example

Runtime Type identification in Java
Determining the Type of object at runtime in Java means finding what kind of object it is. For those who are not familiar with What is a Type in Java, Type is the name of class e..g for “abc” which is a String object, Type is String. Finding the Type of any object at runtime is also known as Runtime Type Identification in Java. Determining Type becomes increasingly important for a method that accepts parameters of type java.lang.An object like compareTo method of the Comparable class. Since two objects of different types can not be equal to each other if we know how to determine the type of object from the object itself then we can, not only avoid ClassCastExcpetion but also optimized the equals method. Java provides three different ways to find the type of an object at runtime like instanceof keyword, getClass(), and isInstance() method of java.lang.Class.

Out of all three only getClass() is the one that exactly finds the Type of object while others also return true if the Type of object is the super type.

As we all know that Java throws ClassCastException if you try to cast an object into the wrong type, which makes finding the type of Object at runtime even more important for robust Java programs, Though typecasting can be minimized by using Generics in Java you still have some places where you need to cast object.

In this Java tutorial, we will see examples of three ways of determining the type of Object from the Java program itself. On the same note Java programming language does not support RTTI(Runtime type Identification) which was C++ capability to find Object type at runtime but as I said Java has its own way of facilitating this.

Java program to determine Type of object at runtime

Here is a test Java program that demonstrates Runtime type identification in Java or in simple words how to find a Type of object . It also examples that how instanceof , getClass() and isInstance() method works and how can we use them to determine Java object type at runtime.

In this Java program, we have three classes; Rule , SystemRule, and BusinessRule . Both SystemRule and BusinessRule are sub-class of Rule . We will create instances of all three classes and then try to find the correct Type for those instances.

The reason we are using both the Superclass and Subclass in this test is because of both instanceof and the isInstance() method of java.lang.Class returns true if the object is of sub-class and we are testing against superclass. Let’s see the program now :

Читайте также:  Encode decode password python

/**
* Java program to determine type of Object at runtime in Java.
* you can identify type of any object by three ways i..e by using instanceof,
* getClass() and isInstance() method of java.lang.Class.
* Java does have capability to find out type of object but its not called
* as RTTI (Runtime type Identification) in C++.
*
* @author Javarevisited
*/

public class RuntimeTypeIdentificationTest

public static void main ( String args []) <
//creating instance of sub class and storing into type of superclass
Rule simpleRule = new BusinessRule () ;

//determining type of object in Java using instanceof keyword
System. out . println ( «Checking type of object in Java using instanceof ==>» ) ;
if ( simpleRule instanceof Rule ) <
System. out . println ( «System rule is instance of Rule» ) ;
>
if ( simpleRule instanceof SystemRule ) <
System. out . println ( «System rule is instance of SystemRule» ) ;
>
if ( simpleRule instanceof BusinessRule ) <
System. out . println ( «System rule is instance of BusinessRule» ) ;
>

//determining type of object in Java using getClass() method
System. out . println ( «Checking type of object in Java using getClass() ==>» ) ;
if ( simpleRule. getClass () == Rule. class ) <
System. out . println ( «System rule is instance of Rule» ) ;
>
if ( simpleRule. getClass () == SystemRule. class ) <
System. out . println ( «System rule is instance of SystemRule» ) ;
>
if ( simpleRule. getClass () == BusinessRule. class ) <
System. out . println ( «System rule is instance of BusinessRule» ) ;
>

//determining type of object in Java using isInstance() method
//isInstance() is similar to instanceof operator and returns true even
//if object belongs to sub class.
System. out . println ( «Checking type of object in Java using isInstance() ==>» ) ;
if ( Rule. class . isInstance ( simpleRule )) <
System. out . println ( «SystemRule is instance of Rule» ) ;
>
if ( SystemRule. class . isInstance ( simpleRule )) <
System. out . println ( «SystemRule is instance of SystemRule» ) ;
>
if ( BusinessRule. class . isInstance ( simpleRule )) <
System. out . println ( «SystemRule is instance of BusinessRule» ) ;
>
>

class Rule <
public void process () <
System. out . println ( «process method of Rule» ) ;
>
>

class SystemRule extends Rule

@Override
public void process () <
System. out . println ( «process method of SystemRule class» ) ;
>
>

class BusinessRule extends Rule

@Override
public void process () <
System. out . println ( «process method of Business Rule class» ) ;
>
>

Output:
Checking type of object in Java using instanceof == >
SystemRule is instance of Rule
SystemRule is instance of BusinessRule

Checking type of object in Java using isInstance () == >
SystemRule is instance of Rule
SystemRule is instance of BusinessRule

If you look at the output you will find that both instanceof keyword and isInstance() also consider sub type object as of Super Type. Only getClass() method returns strict type identification result and does not consider sub class object as of Super class. That’s one of the reason programmer prefer to use getClass() over instanceof while overriding equals method in Java.

Important points to remember about Runtime Type Identification in Java

Few points which is worth remembering while determining Type or Class of object from Java program during runtime:

1) Always determine Type while writing methods that accept Object, which not only reduces error but also results in a robust program. You can also use Generics feature to write a parameterized method which is better than the method which accepts raw types.

Читайте также:  Start windows service in java

2) Type identification is also useful before type casting any object into another Type to avoid ClassCastException .

3) Another use of Runtime Type identification is to implement type-specific features on methods which accepts general Type like Object or any interface.

That’s it on Runtime type identification or determining Type of object at runtime in Java program. we have seen a couple of ways to do this like instanceof operator, getClass() and finally isInstance() method of java.lang.Class. If you look at the output closely you might have figured out that except getClass() other two ways of finding Type of object also return true if the object is of Supertype and that’s why getClass() is the preferred way and I always use it while overriding equals() and hashCode() methods.

Remember Java does not support Runtime Type Identification (RTTI) as supported in C++ but does provide a few API methods to find objects at runtime.

Источник

Get Type of Object in Java

Get Type of Object in Java

  1. Get Object Type Using getClass() in Java
  2. Get Object Type Using instanceOf in Java
  3. Get Type of a Manually Created Class Object in Java

In this article, we’ll learn how to get the type of object in Java. It’s helpful to check the object type when the object comes from a source. It’s a place where we can’t verify the type of objects, such as from an API or a private class that we don’t have access to.

Get Object Type Using getClass() in Java

In the first method, we check the type of Object of wrapper classes like Integer and String . We have two objects, var1 and var2 , to check the type. We’ll use the getClass() method of the Object class, the parent class of all objects in Java.

We check the class using the if condition. As the wrapper classes also contain a field class that returns the type, we can check whose type matches with var1 and var2 . Below, we check both the objects with three types.

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 

Get Object Type Using instanceOf in Java

Another method to get the type of object in Java is by using the instanceOf function; it returns if the object’s instance matches with the given class. In this example, we have the objects var1 and var2 that are checked with these three types: Integer , String , and Double ; if any of the conditions meet, we can execute a different code.

Because var1 is of type Integer , the condition var1 instanceOf Integer will become true, and var2 is Double so, var2 instanceOf Double will become true.

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 

Get Type of a Manually Created Class Object in Java

We checked the types of wrapper classes, but in this example, we get the type of three objects of three manually-created classes. We create three classes: ObjectType2 , ObjectType3 and ObjectType4 .

ObjectType3 inherits ObjectType4 , and ObjectType2 inherits ObjectType3 . Now we want to know the type of objects of all these classes. We have three objects, obj , obj2 , and obj3 ; we use both the methods that we discussed in the above examples that are getClass() and instanceOf .

However, there differences between the type of obj2 . The obj2 variable returned the type ObjectType4 while its class is ObjectType3 . It happens because we inherit the ObjectType4 class in the ObjectType3 and the instanceOf checks all the classes and subclasses. The obj returned ObjectType3 because the getClass() function checks only the direct class.

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.

Related Article — Java Object

Copyright © 2023. All right reserved

Источник

Оцените статью