為了講解這個問題,我們先來看一下下面的代碼:
package com.yonyou.test; import java.util.Date; class Test extends Date{ private static final long serialVersionUID = 1L; public static void main(String[] args) { new Test().print(); } public void print(){ System.out.println("當前運行類的名字為:"+super.getClass().getName()); System.out.println("當前運行類的名字為:"+this.getClass().getName()); System.out.println("當前運行類的繼承的父類的名字為:"+this.getClass().getSuperclass().getName()); } }
上面代碼的輸出結果什么樣的呢?
也許你需要上機調試一下,因為有些不確定,下面我們就一起來分析一下:
上機調試后發現運行的結果為:
當前運行類的名字為:com.yonyou.test.Test
當前運行類的名字為:com.yonyou.test.Test
當前運行類的繼承的父類的名字為:java.util.Date
先來分析一下getClass()究竟返回的是什么:
插卡jdk的源碼可以看到如下內容:
/**
* 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.
* @see <a href="http://java.sun.com/docs/books/jls/">The Java
* Language Specification, Third Edition (15.8.2 Class
* Literals)</a>
*/
public final native Class<?> getClass();
一定要看上面注釋中的藍色部分的英文注釋,意思是返回對應的當前正在運行時的類所對應的對象,那么super可以理解為Test的父類Date,
那么請問當前Date類正在運行時的對象是誰?沒錯,就是其子類Test,所以this.getClass(0.getName()和super.getClass().getName()返回的
都是com.yonyou.test.Test
再看看getSuperClass()的源碼
/**
* Returns the <code>Class</code> representing the superclass of the entity
* (class, interface, primitive type or void) represented by this
* <code>Class</code>. If this <code>Class</code> represents either the
* <code>Object</code> class, an interface, a primitive type, or void, then
* null is returned. If this object represents an array class then the
* <code>Class</code> object representing the <code>Object</code> class is
* returned.
*
* @return the superclass of the class represented by this object.
*/
public native Class<? super T> getSuperclass();
沒錯,這里藍色標注的才是返回當前實體類的父類。所以要返回當前類的父類的話,請使用下面這中方式
super.getClass().getSuperClass().getName();