zoukankan      html  css  js  c++  java
  • Is it always safe to call getClass() within the subclass constructor?(转)

    An article on classloading states that the method getClass() should not be called within a constructor because:

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

    The example they gave was:

    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.
        }
    }

    However from what I know, the native final method getClass() will always return the java.lang.Class object of that object instance, regardless of where it's called (within the constructor or not).

    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?

    shareimprove this question
     

    3 Answers

    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?

    Using getClass() in constructor in this manner will always result in a compilation error, since thiscannot be referenced before super() has been called.

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

    You can test it yourself on http://ideone.com/B0nYZ1.

    The Class is ready, but the instance can't be used to reference the Class yet.

    Still, you can use the Class reference in constructor, but you have to do it in a slightly different way: super(MyClassLoader.class.getClassLoader())

    Also, you are free to use getClass() in your constructor after the supertype constructor has been called - as you already pointed out, the object is basically ready after that and the Class reference can be inferred from the instance.

    http://stackoverflow.com/questions/25561873/is-it-always-safe-to-call-getclass-within-the-subclass-constructor

  • 相关阅读:
    用户模版
    VC让对话框显示就最大化
    C#中char[]与string之间的转换
    c#调用C++DLL参数对应
    解决:对 PInvoke 函数的调用导致堆栈不对称问题 <转载>
    git 命令的使用
    me 云面试
    Django 自定义模板语法
    Django session 源码流程
    云计算的介绍
  • 原文地址:https://www.cnblogs.com/softidea/p/4832857.html
Copyright © 2011-2022 走看看