Java: get variable class

For debugging purposes, I would like to display the type of a specific variable in Java, for example:

String s = "adasdas"; System.out.println( SOME_MAGIC_HERE(s) ); 

And we get:

 String 
+4
source share
2 answers

You are looking for the Object.getClass() method.

<strong> Examples:

 System.out.println(s.getClass()); // Prints "java.lang.String" System.out.println(s.getClass().getSimpleName()); // Prints "String" 
+12
source

The following code will show the canonical class name and the simple class name.

 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 
+1
source

Source: https://habr.com/ru/post/1400853/


All Articles