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

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章