Below I will explain in code form:
1 Packagecn.itcast_02;2 3 ImportJava.lang.reflect.Constructor;4 5 ImportCn.itcast_01.Person;6 7 /*8 * Get the construction method through reflection and use. 9 */Ten Public classReflectdemo { One Public Static voidMain (string[] args)throwsException { A //Get bytecode File object -Class C = Class.forName (" Cn.itcast_01.Person"); //Here The red font is the configuration file, in the future we just change the configuration file, loading another class construct, convenient - the //Get Construction Method - //public constructor[] GetConstructors (): All common constructor Methods - //Public constructor[] Getdeclaredconstructors (): All construction methods - //constructor[] cons = C.getdeclaredconstructors (); + //For (Constructor con:cons) { - //System.out.println (con); + // } A at //get a single constructor method - //Public constructor<t> GetConstructor (class<?> ... parametertypes) - //parameters are: The number of construction parameters you want to get, and the class byte-code file object of the data type -Constructor con = c.getconstructor ();//The constructor method object is returned - - //Person p = new Person (); in //System.out.println (p); - //Public T newinstance (Object ... initargs) to //use the constructor method represented by this Constructor object to create a new instance of the Declaration class for the constructed method, and initialize the instance with the specified initialization parameters. +Object obj =con.newinstance (); - System.out.println (obj); the * //Person p = (person) obj; $ //p.show ();Panax Notoginseng } -}
(1) using public constructor[] GetConstructors (), and then using the enhanced for loop to traverse, and then know the following results: We found that only the common construction method can be traversed.
(2) Use public constructor[] Getdeclaredconstructors (): Then use the enhanced for loop to traverse, and then learn the following: We found that we can traverse all construction methods.
(3) Use public constructor[] Getdeclaredconstructors (): We add a private construct to the original person class, and then iterate with the enhanced for loop, We then learned that we could traverse all the construction methods. Including just our definition of the private structure, is not feeling very good!!!
Android (Java) Learning Note 107: Get a construction method through reflection and use