I have a method that attempts to check the type of a given object:
public void test(Object value) {
if (value.getClass() == Integer) {
System.out.println("This is an Integer");
} else if (value.getClass() == String) {
System.out.println("This is a String");
} else if (value.getClass() == Float) {
System.out.println("This is a Float");
}
}
However, this method is not working as expected when calling:
test("Test");
test(12);
test(10.5f);
How can I correctly use java get type of object
to identify and compare object types properly?
Been working with Java for over a decade now, and for quick, reliable checks, instanceof
has always been my go-to.
If you’re trying to java get type of object, using instanceof
is one of the most straightforward and widely accepted ways:
public void test(Object value) {
if (value instanceof Integer) System.out.println("This is an Integer");
else if (value instanceof String) System.out.println("This is a String");
else if (value instanceof Float) System.out.println("This is a Float");
}
It plays really well with inheritance and polymorphism. So if you’re dealing with a class hierarchy, instanceof
is your safest bet.
Yup, agree with @emma-crepeau! Though I’d add—sometimes you want precision. In those cases, getClass()
is worth considering.
While instanceof
works great for most scenarios, if you’re trying to java get type of object exactly, and inheritance isn’t a concern, getClass()
is more strict:
public void test(Object value) {
if (value.getClass() == Integer.class) System.out.println("This is an Integer");
else if (value.getClass() == String.class) System.out.println("This is a String");
else if (value.getClass() == Float.class) System.out.println("This is a Float");
}
This ensures no subclassing trickery—just pure class equality. That said, it’s not polymorphic-friendly.
Both points are valid. I’ll just take it a step further with generics—especially if you’re aiming for type safety and flexibility.
If you’re dynamically working with various types and want a cleaner way to java get type of object, generics offer a nice middle ground:
public <T> void test(T value) {
System.out.println("This is a " + value.getClass().getSimpleName());
}
It’s concise, flexible, and great for debugging or logging purposes.
Final tip: Use instanceof
for inheritance-aware checks, getClass()
for exact matches, and generics when you want to handle any type in a clean, reusable way. All three help when you’re working to java get type of object efficiently. 