getClass()

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.
     *
     * 

The actual result type is {@code Class} * where {@code |X|} is the erasure of the static type of the * expression on which {@code getClass} is called. For * example, no cast is required in this code fragment:

* *

* {@code Number n = 0; }
* {@code Class c = n.getClass(); } *

* * @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()

你可能感兴趣的:(Java)