How do you know a variable type in java?
451,174
Solution 1
a.getClass().getName()
Solution 2
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
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
Solution 4
I learned from the Search Engine(My English is very bad , So code...) How to get variable's type? Up's :
String str = "test";
String type = str.getClass().getName();
value: type = java.lang.String
this method :
str.getClass().getSimpleName();
value:String
now example:
Object o = 1;
o.getClass().getSimpleName();
value:Integer
Solution 5
Use operator overloading feature of java
class Test {
void printType(String x) {
System.out.print("String");
}
void printType(int x) {
System.out.print("Int");
}
// same goes on with boolean,double,float,object ...
}
Related videos on Youtube
Comments
-
Miguel Ribeiro about 2 years
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?-
Joachim Sauer about 14 yearsAre you really interested in the type of the variable? Or do you care about the type of the value? Because the type of the variable can't easily be gotten (in fact it's not possible at all for local variables and requires reflection for fields).
-
Paul Tomblin about 14 years@Joachim, what exactly is the difference between "type of the variable" and "type of the value"?
-
Michael Borgwardt about 14 years@Paul: Consider
Object o = "o";
- the type of the variable is Object, the type of the value is String. -
Ben Lings about 14 years@Paul In
List<String> l = new ArrayList<String>();
, the type of the variable isList<String>
, the type of the value isArrayList<String>
. -
Ajay Takur over 10 years@Ben Lings The type of variable is java.util.ArrayList and the type of value is java.util.ArrayList.
-
Ben Lings over 10 years@AjayThakur - it's the difference between the compile-time (static) type and the runtime (dynamic) type.
-
-
Joachim Sauer about 14 yearsThat will give the type of the value. not necessarily the type of the variable.
-
Martin about 14 yearsI just figured that was what the OP was really looking for since the declaration of
a
is pretty obvious at compile time -
Miguel Ribeiro about 14 yearsThat would work if the types aren't primitives... If the type is int , how to know the type?
-
Joachim Sauer about 14 years@Miguel: since the only way you can handle an
int
value is in anint
variable, there's no way to write code that handles aint
value and doesn't know that type. The matter is different in case you're handling a wrapper likeInteger
, but then the code of this answer works again. -
Mehdi over 8 yearsthis is not true for a primitive type.
-
nicoschl over 7 yearsJava does not have the concept of operator overloading, this is method overloading
-
skomisa about 6 yearsFor "but you will also get subclasses returning true...", I think you meant "but you will also get parent classes returning true...", right?
-
seokhoonlee almost 6 yearsaren't you Martin as well? :)
-
chankruze over 4 yearsThe other Martin ... LOL ;)
-
Alex78191 about 4 yearsThic code
Double a = 1d; boolean b = a instanceof String;
will cause errorerror: incompatible types: Double cannot be converted to String
-
shevy about 4 yearsI come from ruby and wanted to test: Integer.parseInt("12").getClass().getName() which evidently does not work. No idea if anyone reads this, but a universal type query method would be great. (I was trying to determine the difference between .valueOf() and .parse* related methods.)
-
shevy about 4 yearsInteresting. I just tried your code on: System.out.println( ( (Object) Integer.parseInt("12") ).getClass().getSimpleName() ); and it works! \o/
-
Yossarian42 almost 4 years@shevy
Integer.parseInt()
return primitive int type, not an instance of Integer class. Instead,(Object Integer.parseInt("12")) wraps the int into an Integer object, which inherits the method
getClass()` fromObject
. -
pradeep karunathilaka over 3 yearsthis is not given for primitive type varibales
-
27px over 3 yearsThank you very much, before the
getSimpleName()
, I tried to use(Stack)(variable.getClass().toString().split(".")).pop()
and it didn't work, I was using JavaScript logic and type casted it into stack to pop the last element after spliting with.
and it didn't work. -
newbie almost 3 yearsbut this fails for a null value :(