mardi 26 avril 2016

How writing classname.class is able to return reference to java.lang.Class object?

According to my knowledge whenever a class gets loaded an object of Class.class gets created for it by JVM, which stores all meta information of the loaded class.

When we use forName("classname") method, it first loads "classname" and then creates Class.class object for it and returns reference to the created Class.class object.

Example.java is given as:

class Example
{
        static
        {
                System.out.println("Example Loaded");
        }
        Example()
        {
                System.out.println("Example Constructed");
        }
}

Use.java is:

import java.lang.reflect.*;
class Use
{
        int i;
        public static void main(String[] args) throws Exception
        {
                Class c = Class.forName("Example");
                Constructor[] con = c.getDeclaredConstructors();
                for(Constructor x: con)
                {
                        System.out.println(x.getName());
                }
        }
}

Running Use.java outputs:

Example Loaded
Example

getClass() is a method which can be used only with objects. So definitely before object creation a class will be loaded and object of Class.class will be created for it.

According to "Class and Data" section of http://ift.tt/1mRz6Ca, "Whenever we compile any Java file, the compiler will embed a public, static, final field named class, of the type java.lang.Class, in the emitted byte code". We can use this field as:

import java.lang.reflect.*;
class Use
{
        int i;
        public static void main(String[] args) throws Exception
        {
                Class c = Example.class;
                Constructor[] con = c.getDeclaredConstructors();
                for(Constructor x: con)
                {
                        System.out.println("Hello "+x.getName());
                }
        }
}

Output of above code is:

Hello Example

Means the class Example did not get loaded. Field "class" is a static member of the class Example and before using a static JVM at least need to load the class.

My doubts are: 1). Why class Example did not get loaded? 2). If class did not get loaded then object of Class.class also not get created for it. Then from where the statement "Class c = Example.class" returning the reference of Class.class.





Aucun commentaire:

Enregistrer un commentaire