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

  • 相关阅读:
    移动web开发之flex布局(弹性布局)
    移动web开发之流式布局
    移动端基础
    3D变形(CSS3) transform
    动画(CSS3) animation
    2D变形(CSS3) transform
    过渡(CSS3)
    CSS精灵技术(sprite)
    字体图标
    伸缩布局(CSS3)
  • 原文地址:https://www.cnblogs.com/softidea/p/4832857.html
Copyright © 2011-2022 走看看