Object 类的 getClass方法

来源:互联网 发布:南大碎尸 知乎 编辑:程序博客网 时间:2024/06/06 07:08

在看一个开源框架的源代码,发现代码里有一个getClass()方法,不知道哪里来的,看代码提示说是object类的一个方法,

Class<? extends Hello> java.lang.Object.getClass()Note: This element neither has attached source nor attached Javadoc and hence no Javadoc could be found.

于是去查了api,发现有如下描述

Class Object is the root of the class hierarchy. Every class has
Object as a superclass. All objects, including arrays, implement the
methods of this class. Object
类是处于Java类的继承层级关系的最顶层,声明的每一个类都以Object类作为超类,

getClass

getClass 用于Java的反射机制,返回这个对象的类,直接在类中使用的时候就是返回当前类。

package demo;public class Hello {     Hello a;    public Hello(){        System.out.println("Hello");    }    public void test(){        try {a = getClass().newInstance();}        catch (Exception e) {throw new RuntimeException(e);}    }    public static void main(String[] args) {        // TODO Auto-generated method stub           //第一次通过构造方法实例化一次           Hello hello = new Hello();           //调用test方法给类中的本类对象实例化           hello.test();    }}

运行结果会发现出现两次Hello
这里写图片描述

0 0
原创粉丝点击