哪个类在基类的构造函数中getClass()报告 [英] Which class does getClass() report inside a constructor of a base class

查看:118
本文介绍了哪个类在基类的构造函数中getClass()报告的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Java中,可以放心地假设在用作基类的类的构造函数中调用 getClass()将提供有关派生类的信息,而不是基类的类?

In Java, is it safe to assume that getClass() called inside a constructor of a class used as a base class will provide information about the derived class, rather than the class of the base class?

它似乎工作,但我想这不一定意味着它的安全。
例如,如果我有以下两个类:

It seems to work, but I guess that doesn't necessarily mean it's safe. For example, if I have the following two classes:

public class Parent {
    public Parent() {
        System.out.println(getClass().getName());
    }
}

和:

public class Derived extends Parent {
    public Derived() {
        super();
    }

    public static void main(String... args) {
        new Derived();
    }
}

当我运行 main ()方法在它打印的Derived类中: Derived (这是我希望的)。但是我可以依靠JVM上的这种行为吗?

When I run the main() method in the Derived class it prints: Derived (which is what I was hoping). But can I rely on that behavior across JVMs?

推荐答案

getClass Object 的方法之一并返回 运行时类:


返回此对象的运行时类。返回的Class对象是被表示类的静态同步方法锁定的对象。

Returns the runtime class of this Object. The returned Class object is the object that is locked by static synchronized methods of the represented class.

code>派生。

So yes, it will always return Derived.

这篇关于哪个类在基类的构造函数中getClass()报告的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆