How can I check a variable's type in Java 8, similar to typeof in JavaScript?

In JavaScript, we use typeof to check a variable’s type, but what’s the closest equivalent to typeof Java in Java 8? While instanceof works for object types, it doesn’t support primitives.

Are there better or more flexible ways in Java 8 to determine the type of a variable at runtime?

Ah yes, I ran into this when switching from JavaScript to Java too.

In Java 8, instanceof is your go-to for checking if an object is of a certain type:

java
Copy
Edit
if (myVar instanceof String) {
    System.out.println("It's a String!");
}

But yeah, this won’t help with primitives like int or double.

For those, you usually already know the type at compile time because Java is statically typed.

If you really need to check dynamically, boxing them into their wrapper classes helps.