How do you know a variable type in java? [duplicate]

Let's say I declare a variable:

String a = "test";

And I want to know what type it is, i.e., the output should be java.lang.String How do I do this?


Solution 1:

a.getClass().getName()

Solution 2:

I would like to expand on Martin's answer there...

His solution is rather nice, but it can be tweaked so any "variable type" can be printed like that.(It's actually Value Type, more on the topic). That said, "tweaked" may be a strong word for this. Regardless, it may be helpful.

Martins Solution:

a.getClass().getName()

However, If you want it to work with anything you can do this:

((Object) myVar).getClass().getName()
//OR
((Object) myInt).getClass().getSimpleName()

In this case, the primitive will simply be wrapped in a Wrapper. You will get the Object of the primitive in that case.

I myself used it like this:

private static String nameOf(Object o) {
    return o.getClass().getSimpleName();
}

Using Generics:

public static <T> String nameOf(T o) {
    return o.getClass().getSimpleName();
}

Solution 3:

If you want the name, use Martin's method. If you want to know whether it's an instance of a certain class:

boolean b = a instanceof String