How to check the type of an object
Short answer
instanceof with a variable name checks the type and casts the object right away:
void main() {
Object value = "hello";
if (value instanceof String text) {
IO.println(text.length());
}
}Output:
5Several types
A switch with patterns picks a branch by type:
String describe(Object value) {
return switch (value) {
case Integer i when i < 0 -> "negative int " + i;
case Integer i -> "int " + i;
case String s -> "string of length " + s.length();
case null -> "null";
default -> "something else: " + value.getClass().getSimpleName();
};
}
void main() {
IO.println(describe(42));
IO.println(describe(-1));
IO.println(describe("abc"));
IO.println(describe(3.14));
IO.println(describe(null));
}Output:
int 42
negative int -1
string of length 3
something else: Double
nullThe exact class
instanceof takes inheritance into account, while getClass() gives the exact class of the object:
void main() {
Object number = 5;
IO.println(number instanceof Number);
IO.println(number.getClass() == Number.class);
IO.println(number.getClass().getName());
}Output:
true
false
java.lang.IntegerCommon mistake
Casting without a check. If the object has a different type, you get an exception:
void main() {
Object value = 42;
String text = (String) value;
}Output:
Exception in thread "main" java.lang.ClassCastException: class java.lang.Integer cannot be cast to class java.lang.String (java.lang.Integer and java.lang.String are in module java.base of loader 'bootstrap')If you check types often, consider polymorphism: a common method in an interface that each class implements in its own way.
Functions used in this recipe
- instanceof — Checks whether an object is an instance of a type and binds a variable of that type.
- switch — Picks a branch by value; as an expression it returns a result.
- Object.getClass() — Returns the runtime class of an object.