Every time a class was loaded into JVM , JVM creates a java.lang.Class object with the name ‘class’ in that class , that contains all the meta data of loaded class . this ‘class’ variable is static variable . For example , When the class ‘A’ was loaded into JVM , then JVM creates java.lang.Class object with the name ‘class’ and it is static variable of class ‘A’ . This ‘class’ variable contains all the meta data of class ‘A’ such as variable names , method names , constructors and access specifiers of class ‘A’ . We can acces this ‘class’ variable at run time in the following ways . Those are .
1) ‘class’ variable is static , So we can get java.lang.Class object by static calling .
java.lang.Class cls = java.lang.String.class // 'class' is the static variable and will be created at runtime by JVM .
2) By calling getClass() method of loaded class .
String s = new java.lang.String();
Class c = s.getClass();
3) By calling getSuperclass() method on Class object that gives super class details.
String s = new java.lang.String(); Class c = s.getClass(); Class c1 = c.getSuperclass();
4) By loading class that is available at run time
If we want to get internal details of a class that is available at runtime, we have to load that class/interface in to main memory using forName(String) method that is available in java.lang.Class. forName(String) is a static factory method. String parameter represents class name You have to pass fully qualified name as argument to forName() method, otherwise it raises ClassNotFoundException.
Class c = Class.forName("java.lang.String");