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

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

}
Share:
451,174

Related videos on Youtube

Miguel Ribeiro
Author by

Miguel Ribeiro

SOreadytohelp

Updated on March 05, 2022

Comments

  • Miguel Ribeiro
    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
      Joachim Sauer about 14 years
      Are 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
      Paul Tomblin about 14 years
      @Joachim, what exactly is the difference between "type of the variable" and "type of the value"?
    • Michael Borgwardt
      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
      Ben Lings about 14 years
      @Paul In List<String> l = new ArrayList<String>();, the type of the variable is List<String>, the type of the value is ArrayList<String>.
    • Ajay Takur
      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
      Ben Lings over 10 years
      @AjayThakur - it's the difference between the compile-time (static) type and the runtime (dynamic) type.
  • Joachim Sauer
    Joachim Sauer about 14 years
    That will give the type of the value. not necessarily the type of the variable.
  • Martin
    Martin about 14 years
    I just figured that was what the OP was really looking for since the declaration of a is pretty obvious at compile time
  • Miguel Ribeiro
    Miguel Ribeiro about 14 years
    That would work if the types aren't primitives... If the type is int , how to know the type?
  • Joachim Sauer
    Joachim Sauer about 14 years
    @Miguel: since the only way you can handle an int value is in an int variable, there's no way to write code that handles a int value and doesn't know that type. The matter is different in case you're handling a wrapper like Integer, but then the code of this answer works again.
  • Mehdi
    Mehdi over 8 years
    this is not true for a primitive type.
  • nicoschl
    nicoschl over 7 years
    Java does not have the concept of operator overloading, this is method overloading
  • skomisa
    skomisa about 6 years
    For "but you will also get subclasses returning true...", I think you meant "but you will also get parent classes returning true...", right?
  • seokhoonlee
    seokhoonlee almost 6 years
    aren't you Martin as well? :)
  • chankruze
    chankruze over 4 years
    The other Martin ... LOL ;)
  • Alex78191
    Alex78191 about 4 years
    Thic code Double a = 1d; boolean b = a instanceof String; will cause error error: incompatible types: Double cannot be converted to String
  • shevy
    shevy about 4 years
    I 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
    shevy about 4 years
    Interesting. I just tried your code on: System.out.println( ( (Object) Integer.parseInt("12") ).getClass().getSimpleName() ); and it works! \o/
  • Yossarian42
    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()` from Object.
  • pradeep karunathilaka
    pradeep karunathilaka over 3 years
    this is not given for primitive type varibales
  • 27px
    27px over 3 years
    Thank 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
    newbie almost 3 years
    but this fails for a null value :(