package org.demo;
public class B {
B() {
System.out.println("B:" + this.getClass());
}
public static void main(String[] args) {
new B();
}
}
输出结果是:
B:class org.demo.B
package org.demo;
public class A extends B {
A() {
super();
System.out.println("A:" + this.getClass());
System.out.println("A:" + super.getClass());
}
public static void main(String[] args) {
new A();
}
}
输出结果为:
B:class org.demo.A
A:class org.demo.A
A:class org.demo.A
不管是A类的getClass()还是B类的getClass(),他们都是非覆盖式的从Object继承来的。
/**
* Returns the runtime class of this {@code Object}. The returned
* {@code Class} object is the object that is locked by {@code
* static synchronized} methods of the represented class.
*
* <p><b>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.</b> For
* example, no cast is required in this code fragment:</p>
*
* <p>
* {@code Number n = 0; }<br>
* {@code Class<? extends Number> c = n.getClass(); }
* </p>
*
* @return The {@code Class} object that represents the runtime
* class of this object.
* @jls 15.8.2 Class Literals
*/
public final native Class<?> getClass();
返回此 Object 的运行时类。返回的 Class 对象是由所表示类的 static synchronized 方法锁定的对象。
如果想要从A中得到B.class,可以用 this.getClass().getSuperClass()