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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With