Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to assign instanceof type to a variable?

I am wondering if it is possible and how to store a type reference into a variable so that it can be later used with the instanceof operator.

For example

Book book = new Book("My Favourite Book", "Some Author");

BookType bookType = Book;

if(book instanceof bookType){
    // Do something
}

Instead of having to hard code it:

Book book = new Book("My Favourite Book", "Some Author");

if(book instanceof Book){
    // Do something
}

Is it possible to get the Book type from Book.class maybe using reflection?

I did not found much about this topic.

Note that this is not the same as using

Book.class.isInstance(book);
Object value = Book.class.cast(book);

because I would lose all the methods of the Book class.

like image 326
1Z10 Avatar asked Apr 27 '26 03:04

1Z10


1 Answers

If you are only going to use it for instanceOf i think you should think about using this structure:

Object someObject = new Book(...);

if(someObject instanceOf Book book) {
    //use book as variable
    book.read();
}

To my knowledge this is called Pattern Matching is is possible in Java 14.

like image 87
DaveLTC Avatar answered Apr 30 '26 21:04

DaveLTC