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();
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值