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


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.


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:


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.

Need Your Help

differences in using equality operator in php


can anybody tell me the difference of using '===' as

-I Flag in GCC ( Linux )

c gcc compiler-flags

I Have found a source file bundle with a Makefile, I went through it, and In CFLAG Variable, There is a FLAG -I , I have searched on the web, But couldn't find what it actually does. Is it something

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.