How do you know a variable type in java?

后端 未结 7 1769
野性不改
野性不改 2020-11-30 18:07

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

7条回答
  •  余生分开走
    2020-11-30 19:01

    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?

提交回复
热议问题