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 this
cannot 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.