4

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
asked Mar 11, 2012 at 16:00
1
  • 3
    +1 for SOME_MAGIC_HERE(s) :D IT WAS AUTOMAGIC! Always nice to get a good laugh! Commented Mar 11, 2012 at 16:04

2 Answers 2

12

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
1
  • Class of an object: s.getClass() Class of a class: String.class Name of a class: clazz.getName() Commented Mar 11, 2012 at 16:06
1

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

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.