How do you know a variable type in java?

JavaVariablesTypes

Java Problem Overview


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?

Java Solutions


Solution 1 - Java

a.getClass().getName()

Solution 2 - 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

Solution 3 - Java

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 - Java

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 - Java

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 ...
    
}

Solution 6 - Java

I think we have multiple solutions here:

  • instance of could be a solution.

Why? In Java every class is inherited from the Object class itself. So if you have a variable and you would like to know its type. You can use

  • System.out.println(((Object)f).getClass().getName());

or

  • Integer.class.isInstance(1985); // gives true

or

  • isPrimitive()

     public static void main(String[] args) {
    
      ClassDemo classOne = new ClassDemo();
      Class classOneClass = classOne();
    
      int i = 5;
      Class iClass = int.class;
    
      // checking for primitive type
      boolean retval1 = classOneClass.isPrimitive();
      System.out.println("classOneClass is primitive type? = " + retval1);
    
      // checking for primitive type?
      boolean retval2 = iClass.isPrimitive();
      System.out.println("iClass is primitive type? = " + retval2);
     }
    

This going to give us:

  1. FALSE
  2. TRUE

Find out more here: https://stackoverflow.com/questions/12361492/how-to-determine-the-primitive-type-of-a-primitive-variable

https://docs.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html

http://docs.oracle.com/cd/E26806_01/wlp.1034/e14255/com/bea/p13n/expression/operator/Instanceof.html

Solution 7 - Java

I agree with what Joachim Sauer said, not possible to know (the variable type! not value type!) unless your variable is a class attribute (and you would have to retrieve class fields, get the right field by name...)

Actually for me it's totally impossible that any a.xxx().yyy() method give you the right answer since the answer would be different on the exact same object, according to the context in which you call this method...

As teehoo said, if you know at compile a defined list of types to test you can use instanceof but you will also get subclasses returning true...

One possible solution would also be to inspire yourself from the implementation of java.lang.reflect.Field and create your own Field class, and then declare all your local variables as this custom Field implementation... but you'd better find another solution, i really wonder why you need the variable type, and not just the value type?

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionMiguel RibeiroView Question on Stackoverflow
Solution 1 - JavaMartinView Answer on Stackoverflow
Solution 2 - JavaAtspulgsView Answer on Stackoverflow
Solution 3 - JavaMartin KonecnyView Answer on Stackoverflow
Solution 4 - JavaCopy_PasteView Answer on Stackoverflow
Solution 5 - Javaepicwhat001View Answer on Stackoverflow
Solution 6 - JavanarancsView Answer on Stackoverflow
Solution 7 - JavaSebastien LorberView Answer on Stackoverflow