For debugging purposes, I would like to display the type of a specific variable in Java, e.g.:
String s = "adasdas";
System.out.println( SOME_MAGIC_HERE(s) );
And get:
String
Adam Matan
asked Mar 11, 2012 at 16:00
-
3+1 for SOME_MAGIC_HERE(s) :D IT WAS AUTOMAGIC! Always nice to get a good laugh!Ryan Amos– Ryan Amos2012年03月11日 16:04:57 +00:00Commented Mar 11, 2012 at 16:04
2 Answers 2
You're looking for the Object.getClass()
method.
Examples:
System.out.println(s.getClass()); // Prints "java.lang.String"
System.out.println(s.getClass().getSimpleName()); // Prints "String"
answered Mar 11, 2012 at 16:01
-
Class of an object:
s.getClass()
Class of a class:String.class
Name of a class:clazz.getName()
Ryan Amos– Ryan Amos2012年03月11日 16:06:09 +00:00Commented Mar 11, 2012 at 16:06
The following code will show the canonical name of the class and the Simple name of the class.
package com.personal.sof;
public class GetClassOfVariable {
public static void main(String[] args) {
String strVar = "Hello World";
System.out.println(strVar.getClass().getCanonicalName());
System.out.println(strVar.getClass().getSimpleName());
}
}
o/p :
java.lang.String
String
answered Mar 11, 2012 at 16:24
lang-java