Java testing object type

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.

Читайте также:  Типы данных чисел python

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 :

/**
* 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
*/

Читайте также:  Admin php mod plugins

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.

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.

Источник

Assert That an Object Is From a Specific Type

announcement - icon

As always, the writeup is super practical and based on a simple application that can work with documents with a mix of encrypted and unencrypted fields.

We rely on other people’s code in our own work. Every day.

It might be the language you’re writing in, the framework you’re building on, or some esoteric piece of software that does one thing so well you never found the need to implement it yourself.

The problem is, of course, when things fall apart in production — debugging the implementation of a 3rd party library you have no intimate knowledge of is, to say the least, tricky.

Lightrun is a new kind of debugger.

It’s one geared specifically towards real-life production environments. Using Lightrun, you can drill down into running applications, including 3rd party dependencies, with real-time logs, snapshots, and metrics.

Learn more in this quick, 5-minute Lightrun tutorial:

announcement - icon

Slow MySQL query performance is all too common. Of course it is. A good way to go is, naturally, a dedicated profiler that actually understands the ins and outs of MySQL.

The Jet Profiler was built for MySQL only, so it can do things like real-time query performance, focus on most used tables or most frequent queries, quickly identify performance issues and basically help you optimize your queries.

Critically, it has very minimal impact on your server’s performance, with most of the profiling work done separately — so it needs no server changes, agents or separate services.

Basically, you install the desktop application, connect to your MySQL server, hit the record button, and you’ll have results within minutes:

announcement - icon

DbSchema is a super-flexible database designer, which can take you from designing the DB with your team all the way to safely deploying the schema.

The way it does all of that is by using a design model, a database-independent image of the schema, which can be shared in a team using GIT and compared or deployed on to any database.

And, of course, it can be heavily visual, allowing you to interact with the database using diagrams, visually compose queries, explore the data, generate random data, import data or build HTML5 database reports.

Get started with Spring 5 and Spring Boot 2, through the Learn Spring course:

1. Overview

In this article, we’ll explore how we can verify that an object is of a specific type. We’ll be looking at different testing libraries and what methods they offer to assert the object type.

The scenario in which we might need to do this can vary. A common one is when we utilize an interface as a return type of a method but then, according to the specific object returned, we want to perform different operations. Unit tests can help us determine if the object returned has the class we expect.

2. Example Scenario

Let’s imagine that we are sorting Trees according to whether they lose their leaves over winter or not. We have two classes, Evergreen and Deciduous, both implementing a Tree interface. We have a simple sorter that returns the correct type according to the name of the tree:

Tree sortTree(String name) < Listdeciduous = List.of("Beech", "Birch", "Ash", "Whitebeam", "Hornbeam", "Hazel & Willow"); List evergreen = List.of("Cedar", "Holly", "Laurel", "Olive", "Pine"); if (deciduous.contains(name)) < return new Deciduous(name); >else if (evergreen.contains(name)) < return new Evergreen(name); >else < throw new RuntimeException("Tree could not be classified"); >>

Let’s explore how we can test what type of Tree is actually returned.

2.1. Testing with JUnit5

If we want to use JUnit5, we can check if the class of our object equals the class we are testing against by using the assertEquals method:

@Test public void sortTreeShouldReturnEvergreen_WhenPineIsPassed()

2.2. Testing with Hamcrest

When using the Hamcrest library, we can use the assertThat and instanceOf methods:

@Test public void sortTreeShouldReturnEvergreen_WhenPineIsPassed()

There is a shortcut version available to us when we import with org.hamcrest.Matchers.isA:

assertThat(tree, isA(Evergreen.class));

2.3. Testing with AssertJ

We can also use AssertJ Core library’s isExactlyInstanceOf method:

@Test public void sortTreeShouldReturnEvergreen_WhenPineIsPassed()

Another way to accomplish the same test is with the hasSameClassAs method:

@Test public void sortTreeShouldReturnDecidious_WhenBirchIsPassed()

3. Conclusion

In this tutorial, we’ve seen a few different examples of verifying the type of an object in unit tests. We’ve shown a simple Junit5 example as well as using methods of Hamcrest and AssertJ libraries. Both Hamcrest and AssertJ offer additional helpful information in their error messages.

As always, the code for this example is available over on GitHub.

announcement - icon

Slow MySQL query performance is all too common. Of course it is. A good way to go is, naturally, a dedicated profiler that actually understands the ins and outs of MySQL.

The Jet Profiler was built for MySQL only, so it can do things like real-time query performance, focus on most used tables or most frequent queries, quickly identify performance issues and basically help you optimize your queries.

Critically, it has very minimal impact on your server’s performance, with most of the profiling work done separately — so it needs no server changes, agents or separate services.

Basically, you install the desktop application, connect to your MySQL server, hit the record button, and you’ll have results within minutes:

Источник

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