Java. getClass() returns a class, how come I can get a string too?

后端 未结 4 1410
广开言路
广开言路 2021-01-02 00:58

When I use System.out.println(obj.getClass()) it doesn\'t give me any error. From what I understand getClass() returns a Class type. Since p

4条回答
  •  -上瘾入骨i
    2021-01-02 01:24

    System.out.println(someobj) is always equivalent to:

    System.out.println(String.valueOf(someobj));
    

    And, for non-null values of someobj, that prints someobj.toString();

    In your case, you are doing println(obj.getClass()) so you are really doing:

    System.out.println(String.valueOf(obj.getClass()));
    

    which is calling the toString method on the class.

提交回复
热议问题