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

CopyObject 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.

Answer from DaveLTC on Stack Overflow
Top answer
1 of 2
14

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

CopyObject 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.

2 of 2
3

The closest to what you originally asked1 for is something like this:

Copy   Class<?> clazz = Book.class;

   Object someObject = new Book(...);
   
   if (clazz.isInstance(someObject)) {
      Object instanceOfClazz = clazz.cast(someObject);
      // ...
   }

(Note that this Q&A - Is there something like instanceOf(Class<?> c) in Java? - directly answers the question in the your question title.)

But you objected that the result of the cast call:

"would lose all the methods of the Book class".

First of all that is not technically correct. The object that instanceOfClazz refers to is still and will always remain a Book. It still has and will always have all of the methods of a Book.

But you do have a point (I think). You cannot use the cast call's result effectively in the above code because you assigned it to a variable whose type is Object. And you cannot call Book methods via a variable / value whose static type is Object.

If instead we had written this:

Copy   Class<Book> clazz = Book.class;

   Object someObject = new Book(...);
   
   if (clazz.isInstance(someObject)) {
      Book book = clazz.cast(someObject);
      // call some `Book` methods.
   }

Now you can call Book methods on book. But the gotcha is that we had to write Class<Book> instead of Class<?> (or Class) to make that work. So we have ended up wiring the class name Book into the code anyway. Ooops!

The fundamental problem is that Java code cannot make regular method calls on an object unless the compiler knows what its type is ... and that it has those methods. If you want to invoke Book methods in cases where the static type of the variable is (say) Object, then you have to use reflection to do it. Something like this:

Copy  if (clazz.isInstance(someObject)) {
      Method method = clazz.getMethod("setNosPages", int.class);
      method.invoke(someObject, 99);
  }

and deal with the various exceptions that that might throw.

Basically, you refer to the class and methods by name in the code, or you use reflection.


"I need to assign the object/value parsed from a json to a field of type Book (or other types accordingly) of another class."

It won't work. Java is a statically typed language2. Think of another way to solve the problem. For example, use reflection to assign to the field.


1 - That is ... what the words of your question originally asked!
2 - OK ... that is over-simplifying.

🌐
Baeldung
baeldung.com › home › java › core java › pattern matching for instanceof in java
Pattern Matching for instanceof in Java | Baeldung
January 16, 2024 - Java 14, via JEP 305, brings an improved version of the instanceof operator that both tests the parameter and assigns it to a binding variable of the proper type.
Discussions

Finalizing in JDK 16 - Pattern matching for instanceof
i cannot parse section 1 at all lol. why would x instanceof Object o result in a "pattern always matches the target" error when x could be null? More on reddit.com
🌐 r/java
24
68
August 27, 2020
Pattern matching for instanceof
Two key reasons: Not backwards compatible. Let's say there are two methods, foo(String) and foo(Object). Currently, Object x= ...; if (x instanceof String) foo(x); calls the Object version. What you want would break existing code rather drastically. Doesn't work in general. The expression you cast, how do you know it can't change? if (field instanceof String) can't treat the type of field as String unless it's final. if (bar() instanceof String) is even more problematic. More on reddit.com
🌐 r/java
39
36
August 21, 2022
🌐
Oracle
docs.oracle.com › en › java › javase › 17 › language › pattern-matching-instanceof-operator.html
Pattern Matching for instanceof - Java
July 14, 2022 - A pattern is a combination of a predicate, or test, that can be applied to a target and a set of local variables, called pattern variables, that are assigned values extracted from the target only if the test is successful. The predicate is a Boolean-valued function of one argument; in this case, it’s the instanceof operator testing whether the Shape argument is a Rectangle or a Circle.
🌐
How to do in Java
howtodoinjava.com › home › java basics › pattern matching for instanceof [java 17]
Pattern Matching for instanceof [Java 17]
November 17, 2022 - if (obj instanceof String s) { // can use 's' here } Note that the pattern will only match, and s will only be assigned, if obj is not null.
🌐
GeeksforGeeks
geeksforgeeks.org › java › pattern-matching-for-instanceof-java-17
Pattern Matching For instanceof Java 17 - GeeksforGeeks
July 23, 2025 - Java 14, via JEP 305, brings an enhanced version of the instanceOf keyword that both tests the parameter object and assigns it to a binding variable of the correct type.
🌐
Javastreets
javastreets.com › blog › java14 › jep305-pattern-matching-for-instanceof.html
Java 14 - Pattern Matching for InstanceOf (Preview) - {Java} Streets
A pattern Matching for instanceOf in Java 14 is simple - If the type of a target matches, then it is assigned to a specified single binding variable.
🌐
Medium
medium.com › tuanhdotnet › pattern-matching-with-instanceof-in-java-17-ebc7e142b8cc
Pattern Matching with instanceof in Java 17 | by Anh Trần Tuấn | tuanhdotnet | Medium
April 24, 2025 - Object obj = "Hello, World!"; if (obj instanceof String str) { System.out.println("String length: " + str.length()); } Here, if obj is an instance of String, it is simultaneously cast and assigned to str. ... Hey there! I am Tuan Anh. I started this blog to share what I have learned as a developer. It is for anyone curious about coding. ... With 6 years of Java web experience, passionate about architecture problem-solving, and tackling complex logical challenges with strong reasoning skills.
🌐
Tutorialspoint
tutorialspoint.com › home › java › java instanceof pattern matching
Java - Pattern Matching with instanceof Operator
September 1, 2008 - Java 14 introduced an enhanced for the instanceof operator in the JEP 305, which tests both the parameter object and assigns it to a binding variable of the appropriate type. The main enhancement is the introduction of the type pattern, which consists of the following two things − · Predicate − It is a Boolean function with one argument, which checks if the target object is an instance of the specified type.
Find elsewhere
🌐
OpenJDK
openjdk.org › jeps › 394
JEP 394: Pattern Matching for instanceof
July 27, 2020 - Because of the semantics of the ... been assigned and so the flow analysis dictates that the variable s is not in scope on the right hand side of the || operator. The use of pattern matching in instanceof should significantly reduce the overall number of explicit casts in Java ...
🌐
Jenkov
jenkov.com › tutorials › java › instanceof.html
Java instanceof operator
The Java instanceof operator can determine whether a given object is an instance of a given class or interface. The Java instanceof operator was updated in Java 14 with pattern matching functionality, making it more concise to use.
🌐
Medium
medium.com › @AlexanderObregon › how-javas-instanceof-operator-works-09071a27cd3b
How Java’s instanceof Operator Works | Medium
February 28, 2025 - Here, if obj is an instance of String, the str variable is automatically declared and assigned inside the if block. This change removes the need for explicit casting and allows the variable to be used immediately. When the Java compiler processes an instanceof check with pattern matching, it generates optimized bytecode that avoids redundant casting operations.
🌐
Baeldung
baeldung.com › home › java › core java › java instanceof operator
Java instanceof Operator | Baeldung
May 11, 2024 - In Java, every class implicitly inherits from the Object class. Therefore, using the instanceof operator with the Object type will always evaluate to true:
🌐
Reddit
reddit.com › r/java › finalizing in jdk 16 - pattern matching for instanceof
r/java on Reddit: Finalizing in JDK 16 - Pattern matching for instanceof
August 27, 2020 - Note that null instanceof Object always returns false, but null instanceof Object o would always return true and assign null to the variable o. I don't know why they decided to do this though and not just let it return false and not assign it. It seems that for any type other than Object, it doesn't match. But with Object the idea of using instanceof Object o is probably to have something which always matches.
🌐
Jchq
jchq.net › certkey › 0501certkey.htm
5.1) Operators and assignments
Note that instanceof tests against a class name and not against an object reference for a class. ... As you might expect the + operator will add two numbers together. Thus the following will output 10 ... The + operator is a rare example of operator overloading in Java.
🌐
Claudiodesio
claudiodesio.com › home › blog › going beyond java 8: pattern matching for instanceof
Going beyond Java 8: pattern matching for instanceof - Claudio De Sio Cesari
June 23, 2022 - It is essential to use the object cast only after checking its validity with the instanceof operator. In fact, the compiler cannot determine if a certain object resides at a certain address instead of another. It is only at runtime that the Java Virtual Machine can use the instanceof operator to resolve any doubts.
🌐
DEV Community
dev.to › paulike › casting-objects-and-the-instanceof-operator-2hgj
Casting Objects and the instanceof Operator - DEV Community
June 10, 2024 - To enable generic programming, it is a good practice to define a variable with a supertype, which can accept an object of any subtype. instanceof is a Java keyword. Every letter in a Java keyword is in lowercase. To help understand casting, you may also consider the analogy of fruit, apple, and orange, with the Fruit class as the superclass for Apple and Orange. An apple is a fruit, so you can always safely assign an instance of Apple to a variable for Fruit.