java - 在子类构造函数中调用 getClass() 总是安全的吗?

标签 java class constructor classloader jls

An article on classloading说明方法 getClass()不应在构造函数中调用,因为:

object initialization will be complete only at the exit of the constructor code.

他们举的例子是:

public class MyClassLoader extends ClassLoader{
    public MyClassLoader(){
        super(getClass().getClassLoader()); // should not call getClass() because object
                                            //    initialization will be complete only at
                                            //    the exit of the constructor code.
    }
}

但是据我所知, native final方法 getClass() 将始终返回 java.lang.Class该对象实例的对象,无论它在何处被调用(是否在构造函数内)。

在构造函数中调用 getClass() ever 会给我们带来问题吗?

如果是这样,在构造函数中调用 getClass() 会给我们带来错误的例子有哪些?

最佳答案

Will calling getClass() within the constructor ever give us problems? If so, what are some examples whereby calling getClass() within the constructor would give us errors?

以这种方式在构造函数中使用 getClass()总是导致编译错误,因为不能在 之前引用 this super() 已被调用。

Main.java:17: error: cannot reference this before supertype constructor has been called
        super(getClass().getClassLoader()); // should not call getClass() because object
              ^
1 error

你可以在http://ideone.com/B0nYZ1上自己测试.

Class 已准备就绪,但实例 还不能用于引用Class

仍然,您可以在构造函数中使用 Class 引用,但您必须以稍微不同的方式来实现:super(MyClassLoader.class.getClassLoader ())

此外,您可以在构造函数中自由使用 getClass() after 父类(super class)型构造函数被调用 - 正如您已经指出的那样,对象基本上准备就绪可以从实例中推断出那个和 Class 引用。

关于java - 在子类构造函数中调用 getClass() 总是安全的吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25561873/

相关文章:

java - 如何从java中的xml节点创建格式化字符串

python - 如何将列表转换为 Flask 模板的类对象

c++ - 未定义的类,无法从 main 到达我的 header

language-agnostic - 构造函数:完整的还是最小的?

java - 定义 Freemarker EOL 格式(\n 而不是\r\n)

java - 编译java程序时出错 'Cannot find symbol'

java - Groovy - 如何在 Groovy 中压缩整个目录?

java - hadoop 使用类名提交作业,为什么需要 job.setJarByClass()?

Java 多重构造函数设置问题

c++ - 如果该类不是 `copy constructor`,是否可以移动对象?