Distinction between ClassObject.getClass,ClassName.class and Class.forName(“ClassName”)

对着背影说爱祢 提交于 2019-11-29 08:54:22

Class.forName loads and initializes the class. obj.getClass() returns the class object loaded into permgen. If the class is loaded by the same classloader == has to return true. When you are see false for == comparison it means that they are loaded by different classloaders.

Yes, they are the same - and they return the exact same object.

Example:

public class Tryout {
    public static class A {     
    }
    public static class B extends A {   
    }
    public static void main(String[] args) throws Exception {
        A a = new A();
        A b = new B();
        //the same class object, one achieved statically and one dynamically.
        System.out.println(a.getClass() == A.class);
        //the same class object using forName() to get class name dynamically 
        System.out.println(Class.forName("Tryout$A") == A.class);
        //different class. B is not A!
        System.out.println(b.getClass() == A.class);
    }
}

Will yield:

true
true
false

Note that the last is yielding false because - though the static type is the same, the dynamic type of B is NOT A, and thus getClass() returns B, which is the dynamic class object of b.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!