Java record-83-reflection mechanism of Java
In the Java Runtime Environment, does the reflection mechanism of the Java language know the attributes and methods of any class? Can any method of an object be called? The answer is yes. This function of dynamically retrieving class information and dynamically calling object Methods comes from the Reflection mechanism of Java. The Java reflection mechanism mainly provides the following functions: 1. determine the class to which any object belongs at runtime; 2. construct any class object at runtime; 3. judge the member variables and methods of any class at runtime; 4. the method that calls any object at runtime; Reflection is a key property of java as a dynamic (or quasi-dynamic) language. This mechanism allows the program to obtain the internal information of any class with a known name through Reflection APIs at runtime, including its modifiers (such as public and static), superclass (such as Object), implements interfaces (such as Serializable), also includes all information about fields and methods, and can change fields content or call methods at runtime. Generally speaking, when talking about dynamic languages, the developer community roughly agrees with the definition: "When a program is running, the program structure or variable type is changed during running. This language is called dynamic language ". From this point of view, Perl, Python, and Ruby are dynamic languages, and C ++, Java, and C # Are not dynamic languages. From the above definition, Java is not a dynamic language, but it has a dynamic mechanism. A Java program can be added to a runtime to learn the class name and its complete structure (excluding the definition of methods ), and generate its object entity, set its fields value, or arouse its methods. This kind of ability to "see through class" is called introspection (introspection, inview, reflection ). Java Reflection API introduction in JDK, the following classes are used to implement the Java Reflection mechanism. lang. in the reflect package: Class: represents a Class; Field Class: represents the member variables of the Class (member variables are also called Class attributes); Method Class: represents the Class Method; Constructor Class: the constructor of classes. Array class: provides static methods for dynamically creating arrays and accessing elements of arrays. In Java, no matter how many objects of a Class are generated, these objects correspond to the same Class object.