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

原文地址:https://www.cnblogs.com/softidea/p/4832857.html