First, why use reflection
In order to write generic code, such as frames. The compile time does not know the type of the incoming object, cannot call methods and properties, so the framework for the purpose of universality, the object is a parameter, only at run time through the class object to get the class information.
Second, what is reflection
The main point is the ability of a program to access, detect, and modify its own state or behavior. In Java, Reflection is a powerful tool. It enables you to create flexible code that can be assembled at run time without the need for source-representative links between components. Reflection allows us to write and execute, allowing our program code to access the internal information of the classes loaded into the JVM, rather than the code of the selected class collaboration in the source code. This makes reflection a primary tool for building flexible applications. However, it should be noted that the cost of reflection is high if used improperly.
Third, how to use
Main methods:
1. Three ways to get class objects
(1) Class.forName ("string full name of the class")
Class<?> clazz = Class.forName ("com.chapter14.Student");
(2) Use Class. class to Get the class object
class<?> clazz = Student.class;
(3) object. GetClass () method
Object object = new Student ();
Class<?> clazz = Object.getclass ();
2. Get the constructor to create the object
(1) Object o = clazz.newinstance (); Object o = new Student ();
(2) using constructor to create objects, with declare is to get all access rights, without declare is to get public
Get all constructors: constructor[] Consarr clazz.getdeclaredconstructors ();
class[] Clazzarr = new Class[]{int.class,string.class,int.class}; Constructor C = clazz.getdeclaredconstructor (Clazzarr);
Object o = c.newinstance (1, "AAA", 22);
3. Get method, call method (for method declared can display 4 kinds of access rights, no declared only public + parent class method)
Get all methods: method[] Methodarr = Clazz.getdeclaredmethods ();
Object. Method name (parameter);
Method name. Invoke (object, parameter);
4. Get Properties
Field name = Clazz.getdeclaredfield ("name"); name.setaccessible (TRUE);//The accessibility of the set Value property destroys the encapsulation
5. Creating arrays Dynamically
string[] Strarr = new STRING[5];
Strarr[0] = "AAA";
Object Objarr = Array.newinstance (String.class, 5);
Technology sharing: www.kaige123.com
This article from the "11247808" blog, reproduced please contact the author!
Java Reflection mechanism