Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
386 views
in Technique[技术] by (71.8m points)

java - Distinction between ClassObject.getClass,ClassName.class and Class.forName("ClassName")

I wish to understand if both Class.forName("ClassName") and ClassObject.getClass return runtime instance of the class. Then why on comparing the resulting Class object obtained from the two fetches us a Boolean false(if we compare using == or equals).
I also want to know what is the exact use of .class method called on the class name.I have read that it is determined at compile time etc but to what purpose. Won't Class.forName("ClassName") suffice??
Thanks

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...