How do you check the runtime type of an object in Java, and how do you use the result safely?
You use getClass() to find out what an object really is, and you use instanceof to ask whether it is of a certain type.
public class Main {
public static void main(String[] args) {
Object o = "hello";
System.out.println(o.getClass().getSimpleName()); // String
System.out.println(o instanceof String); // true
}
}
And there are several ways to ask, and they give different amounts of detail.
Object o = "hello";
o.getClass(); // the class object, which is String.class
o.getClass().getSimpleName(); // the name without the package, String
o.getClass().getName(); // the full name with the package
o instanceof String; // true or false
And how do you use the result safely? With the pattern matching that came in with Java 16, because it does the check and the cast in one step and cannot be got wrong.
if (o instanceof String s) {
// s is already a String here, and it cannot be wrong.
System.out.println(s.length());
}
And the older form has to check first and then cast, because the cast is done at runtime and the check is done by you.
if (o instanceof String) {
String s = (String) o;
System.out.println(s.length());
}
And there are two details worth knowing about. The first one is that the check has to happen before the cast, so the older form is two lines and the newer one is one. And the second one is that the check and the cast have to be close together, because if something changes the object in between then the cast could fail.
the form the risk
-------------------------------- ------------------------------------
(String) o directly it throws if the object is not a
String
instanceof then cast safe, if the two lines are together
instanceof with a pattern safe, and it is one line
And there is one more thing about the getClass approach. It gives you the exact class and not just a kind, so if the object is a StringBuilder and you check for CharSequence then the check passes. That is what makes it different from the instanceof check, which is about the whole family.
Object o = new StringBuilder("hi");
o instanceof CharSequence; // true, a StringBuilder is one
o.getClass() == String.class; // false, it is a StringBuilder
So the rule to remember is this. Use instanceof with a pattern for the check and the cast together.
The last question in this topic is about why the type check is usually a design problem.