java中getClass()和getSuperClass()的讲解
转载
为了讲解这个问题,我们先来看一下下面的代码:
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();