Reflection of Java basics and java reflection
The reflection library provides a rich and well-designed set of tools to write programs that can dynamically manipulate Java code. Programs capable of analyzing class capabilities become reflection ). The reflection mechanism is extremely powerful and can be used to: analyze the ability of classes during running; view objects during running; implement common array operation code; Use Method objects, this object is similar to the function pointer in C ++.
During the running of the program, the Java runtime system always maintains a type identifier called runtime for all objects. This information tracks the class to which each object belongs. The Virtual Machine selects the corresponding method for execution based on the running type information. However, you can access this information through a dedicated Java class. The Class that saves the information is called Class. The getClass () method in the Object Class returns an instance of the Class type.
A Class is a Class in the java. lang package. Its instances can help programs create instances of other classes or obtain internal information of objects of other classes.
Instantiate an object using Class
The most common way to create an object is to use the new operator and the constructor of the Class. In fact, you can also use the Class object to get an instance of a Class. The procedure is as follows:
Note: When you use a Class object to call newInstance () to instantiate a className Class object, the className Class must have a constructor with no parameters.
Obtains information about a class.
When a Class is loaded and an object is created, an object of the Class type associated with the Class is automatically created. Any object calls getClass () methods can obtain a Class object related to this object. This Class object can call the following method to obtain information about the object, for example, the Class Name of the object, the method name in the class, the name of the member variable, and so on.
1 import java.lang.reflect.*; 2 import java.util.Date; 3 4 public class Example { 5 public static void main(String[] args) { 6 Date date = new Date(); 7 Class cs = date.getClass(); 8 String className = cs.getName(); 9 Constructor[] con = cs.getDeclaredConstructors();10 Field[] field = cs.getDeclaredFields();11 Method[] method = cs.getDeclaredMethods();12 13 System.out.println("className:" + className);14 System.out.println("class constructors:");15 for (Constructor c : con) {16 System.out.println(c.toString());17 }18 System.out.println("class fields:");19 for (Field f : field) {20 System.out.println(f.toString());21 }22 System.out.println("class methods:");23 for (Method m : method) {24 System.out.println(m.toString());25 }26 }27 }
Reflection: the implementation of common array operation code and the use of Method are not used for the moment, and do not write ......