先来代码
class="java" name="code">
package test;
public class TestGetClass {
public static void main(String[] args) {
A a1 = new A();
Object o1 = new A();
System.out.println(a1.getClass().getSimpleName());
System.out.println(o1.getClass().getSimpleName());
System.out.println(o1.getClass().getSuperclass().getSimpleName());
}
}
class A {
}
结果贴出来:
A
A
Object
原因很简单,就是因为getClass()方法返回的是运行时的类名。一下是getClass()源码的部分
注释:
The actual result type is {@code Class<? extends |X|>}
* where {@code |X|} is the erasure of the static type of the
*
expression on which {@code getClass} is called.