How do you know a variable type in java?

后端 未结 7 1749
野性不改
野性不改 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:02

    I would like to expand on Martin's answer there...

    His solution is rather nice, but it can be tweaked so any "variable type" can be printed like that.(It's actually Value Type, more on the topic). That said, "tweaked" may be a strong word for this. Regardless, it may be helpful.

    Martins Solution:

    a.getClass().getName()
    

    However, If you want it to work with anything you can do this:

    ((Object) myVar).getClass().getName()
    //OR
    ((Object) myInt).getClass().getSimpleName()
    

    In this case, the primitive will simply be wrapped in a Wrapper. You will get the Object of the primitive in that case.

    I myself used it like this:

    private static String nameOf(Object o) {
        return o.getClass().getSimpleName();
    }
    

    Using Generics:

    public static  String nameOf(T o) {
        return o.getClass().getSimpleName();
    }
    

提交回复
热议问题