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/