views:

192

answers:

3

I wanted a thing like I declare a variable:

String a = "test";

And want to know what type it is, i.e., the output should be java.lang.String

+3  A: 
a.getClass().getName()
Martin
That will give the type of the value. not necessarily the type of the variable.
Joachim Sauer
I just figured that was what the OP was really looking for since the declaration of `a` is pretty obvious at compile time
Martin
That would work if the types aren't primitives...If the type is int , how to know the type?
Miguel Ribeiro
@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.
Joachim Sauer
+1  A: 

If you want the name, use Martins method. If you want to know whether its an instance of a certain class:

boolean b = a instanceof String

teehoo
A: 

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?

Sebastien Lorber