How do you know a variable type in java?
Expanding on Martin's answer...
Martins Solution
a.getClass().getName()
Expanded Solution
If you want it to work with anything you can do this:
((Object) myVar).getClass().getName()
//OR
((Object) myInt).getClass().getSimpleName()
In case of a primitive type, it will be wrapped (Autoboxed) in a corresponding Object variant.
Example #1 (Regular)
private static String nameOf(Object o) {
return o.getClass().getSimpleName();
}
Example #2 (Generics)
public static <T> String nameOf(T o) {
return o.getClass().getSimpleName();
}
Additional Learning
- Material on Java Types, Values and Variables: https://docs.oracle.com/javase/specs/jls/se7/html/jls-4.html
- Autoboxing and Unboxing: https://docs.oracle.com/javase/tutorial/java/data/autoboxing.html
- Docs on Pattern Matching for instanceof: https://docs.oracle.com/en/java/javase/14/language/pattern-matching-instanceof-operator.html
a.getClass().getName()