There are three ways to get the class object:
1.Class c= class name. Classes;
Use this method to get the class object, note that if the class is not loaded, it will not initialize the class
2:Class c= object. GetClass ();
Returns the object of the class that the object really belongs to (when it is converted to a parent class, if this is the case, then the class object that the object actually belongs to) is, for example:
A a=new B ();//b is a subclass of a. Then calling A.getclass () is the class object that corresponds to category B.
3:class c=class.forname ("Class name");
This way you can get a class object, and if the class is not loaded it will initialize the class.
View the differences in initialization of the. class and Class.forName ().
class demo1{final static String s= "Demo1"; static {System.out.println ("demo1 initialized");} Demo1 () {System.out.println ("Newinstance calls the default parameterless constructor");}} Class demo2{static String s= "Demo2"; static {System.out.println ("demo2 initialized");}} Class demo3{static String s= "Demo3"; static {System.out.println ("Demo3 initialized");}} public class classandclassfornametest{public static void Main (string[] args) throws ClassNotFoundException, Instantia Tionexception, Illegalaccessexception{system.out.println ("------------Class.class Way--------------");// System.out.println (DEMO1.S);//This sentence proves that using the final static constant does not require the initialization of the class class<demo1> c=demo1.class;//only the class is loaded, and there is no initialization class. C.newinstance ();//Create an instance from a class object and initialize the class, and call the parameterless constructor System.out.println ("------------new class Mode--------------"); Demo2 instance=new Demo2 ();//This is sure to know that initialization of class System.out.println ("------------class.forname mode--------------"); Class<demo3> f= (class<demo3>) class.forname ("Demo3");//Initialization of Class} when using Class.forName ()
Output Result:
------------Class.class Mode--------------------------New Class Mode--------------Demo2 is initialized------------class.forname mode--------------DEMO3 initialized
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Comparison of Class.forName () with class name. Class and GetClass ()