super.getClass()与this.getClass()

原文地址:http://leihuang.org/2014/11/14/getClass-method/


首先看一段代码:

import java.util.Date;
public  class Test extends Date{
    public static void main(String[] args) {
        new Test().test();
    }
    public void test(){
        System.out.println(super.getClass().getName());
    }
}


上面这段代码的输出为:Test

可能你会奇怪为什么输出的是Test,而不是Date呢?我明明是调用的super.getClass()啊。我们先不急,先来了解一下getClass()方法的机制是什么。以下时getClass()在Object类中实现的源代码。

Returns the runtime classof this Object. The returned Class object is the object that is locked by static synchronized methods of the represented class. The actual result type is Class<? extends |X|> where |X| is the erasure of the static type of the expression on which getClass is called. For example, no cast is required in this code fragment: Number n = 0; Class<? extends Number> c = n.getClass(); Returns: The Class object that represents the runtime class of this object.

public final native Class<?> More ...getClass();

从上面我们能够得知两点:

  1. getClass()方法: 返回此 Object 的执行时类。返回的 Class 对象是由所表示类的 static synchronized 方法锁定的对象。

  2. getClass()时final方法。子类无法重写。

第一点我们能够得出:

什么是执行时类。执行时类是Object的一个实例,注意了,关键来了。他返回的不是Object.class。他返回的是执行时类,就是虚拟机中是谁在执行就是谁,假设你new Date(),Date当然是执行时类。而不是Object,否则全部类的getClass()方法都返回了Object.class 了。

依据上一段解释。Date是Object的子类,Date.getClass()返回的肯定是Date.class,

相同的Test继承Date。假如有一个属于Date的getClass()他返回的也不可能是Date.class,由于当new Test()后,Test是一个执行时类,仅仅只是他拥有Date的资源结构。所以谁被实例化,谁就是一个执行时类。

第二点我们能够得出

上面我们讨论了,Object中getClass()方法返回的是执行时类对象,谁被实例化。getClass()就得到谁。但那仅仅是Object中的getClass()方法而已,而我们时调用的Date.getClass(),or Test.getClass().

这里就涉及到getClass()方法在Object中时final方法了。因此子类是无法重写getClass方法的,所以无论是Date.getClass()还是Test.getClass()。事实上调用的都是Object中的getClass()方法。这样就保证了会遵循第一点。

假设想要从Test中得到Date.class,能够用Test.getClass().getSuperClass();


2014-11-14 12:06:54

Brave,Happy,Thanksgiving !


版权声明:本文博主原创文章。博客,未经同意不得转载。

原文地址:https://www.cnblogs.com/lcchuguo/p/4804990.html