What is Reflection (Reflection).
The main point is that the program can access, detect and modify its own state or behavior of a capability of Java reflection.
In the Java Runtime environment, for any class, you can tell what properties and methods the class has. Can call any one of its methods for any object
The Java reflection mechanism mainly provides the following features:
* 1. Determine the class that any object belongs to at run time.
* 2. Constructs an object of any class at run time.
* 3. Determine the member variables and methods that any class has at run time.
* 4. A method that invokes any object at run time.
Reflectio
Reflection is a key feature 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 the reflection APIs at run time.
Includes all information about its modifiers (such as public, static, etc.), superclass (such as object), implemented interfaces (for example, serializable), and also includes its fields and methods. You can change fields content or call methods at run time. Dynamic Language
The definition of a dynamic language "when a program is run, allows you to change the program structure or variable type, which is called a dynamic language."
From this point of view, Perl,python,ruby is a dynamic language, c++,java,c# is not a dynamic language.
Although Java is not a dynamic language in this definition and classification, it has a very prominent dynamic correlation mechanism: Reflection. The meaning of this word is: reflection, image, reflection, in Java refers to the classes that we can load, detect and use during compilation.
In other words, a Java program can load a class that knows its name at run time, learns its full structure (but does not include methods definitions), generates its object entity, or sets a value on its fields, or evokes its methods.
This ability to "see Through" class (the ability of the program to examine itself) is called introspection (introspection, internal, introspection). Reflection and introspection are two terms that are often mentioned. Introduction to the Java Reflection API
In JDK, the Java reflection mechanism is implemented primarily by the following classes (except the first one) in the Java.lang.reflect package
Class Classes: Represents a class, located under the Java.lang package.
Field class: Represents a member variable of a class (a member variable is also called a property of a class).
Method classes: Methods that represent classes.
Constructor class: Represents the construction method of a class.
Array class: Provides a static method for dynamically creating an array and accessing the elements of an array. Class Object
To use reflection, you first need to get the class object for the classes you want to manipulate.
In Java, these objects correspond to the same class object, regardless of how many objects are generated for a class.
This class object is generated by the JVM and is able to learn about the structure of the entire class.
Common 3 ways to get a class object:
1. Use static methods of class classes. For example:
Class.forName ("java.lang.String");
2. Use the. class syntax for classes. Such as:
String.class;
3. Use the GetClass () method of the object. Such as:
String str = "AA";
Class routine 1: Getting Methods
The routine Dumpmethods class demonstrates the basic role of the reflection API, reading the class name specified by the command-line arguments, and then printing the method information that the class has.
Import Java.lang.reflect.Method;
public class Dumpmethods
{public
static void Main (string[] args) throws Exception//After the method is added, the exception disappears
{
Gets the class object
class<?> ClassType = Class.forName ("java.lang.String") of the classes identified by the string, and/or the string to specify the class name. So the parameter gain can be a run-time behavior that can be args[0]
//returned to the class or interface corresponding to the class object, the array of all methods declared (including Private method)
method[] methods = Classtype.getdeclaredmethods ();
Traversal outputs all method declarations for
(Method:methods)
{
System.out.println (methods);
}}
Routine 2: Calling a method through reflection
invokes the method by reflection. See Code and comments for details:
Import Java.lang.reflect.Method;
public class Invoketester {public int add (int param1, int param2) {return param1 + param2;
public string Echo (String message) {return ' Hello: ' + message; public static void Main (string[] args) throws Exception {//Previous conventional execution method Invoketester tester = n
EW Invoketester ();
System.out.println (Tester.add (1, 2));
System.out.println (Tester.echo ("Tom"));
System.out.println ("---------------------------"); By the way of reflection//The first step, get the Class object//Before the method is: Class.forName () method to get//here with the second method, class name. class class<
?> ClassType = Invoketester.class;
To generate a new object: Using the Newinstance () method Object invoketester = Classtype.newinstance (); System.out.println (Invoketester instanceof Invoketester); Output true//By reflection calling method///First you need to obtain the method object that corresponds to the approach Addmethod = Classtype.getmethod ("Add", new
Class[] {int.class, Int.class}); The first parameter is the method name, and the second parameter is the array of the class object of the parameter that this method needs to call the target method Object result = Addmethod.invoke (Invoketester, New OBJ
Ect[] {1, 2}); SYSTEM.OUT.PRINTLN (result); At this point, result is the integer type//Call the second method Echomethod = Classtype.getdeclaredmethod ("echo", new Class[]{strin
G.class});
Object result2 = Echomethod.invoke (invoketester, New object[]{"Tom"});
System.out.println (RESULT2); }
}
Build Object
If you want to generate objects from a class without a parameter constructor, there are two ways:
1. First get the class object, and then through the class object's Newinstance () method to generate directly:
class<?> ClassType = String.class;
Object obj = classtype.newinstance ();
2. First get the class object, then obtain the corresponding constructor object through the object, and then through the constructor object Newinstance () method to generate
(where the customer is a custom class, there is a constructor without parameters, and a constructor with parameters):
class<?> ClassType = Customer.class;
Gets the constructor object, where the
constructor cons = Classtype.getconstructor (new class[] {}) of the first parameterless construction method is obtained;
Constructs a method to generate an object
obj = cons.newinstance (new object[] {});
To generate an object by using a class's constructor with parameters, you can use only one of the following methods:
(Customer is a custom class that has constructor methods with no parameters, a constructor with parameters, incoming strings, and integral types)
class<?> ClassType = Customer.class;
Constructor cons2 = Classtype.getconstructor (new class[] {string.class, int.class});
Object obj2 = cons2.newinstance (new object[] {"Zhangsan", 20});
You can see that the method that invokes the construction method to generate the object is similar to calling a generic method, unlike fetching a constructor object from a class object without specifying a name, while getting the methods object requires specifying a name. reference materials
Long Zhang teacher Java se instructional video.
Document Links:
Class:
Http://docs.oracle.com/javase/7/docs/api/java/lang/Class.html
Field:
Http://docs.oracle.com/javase/7/docs/api/java/lang/reflect/Field.html
Method:
Http://docs.oracle.com/javase/7/docs/api/java/lang/reflect/Method.html
Constructor:
Http://docs.oracle.com/javase/7/docs/api/java/lang/reflect/Constructor.html
Array:
Http://docs.oracle.com/javase/7/docs/api/java/lang/reflect/Array.html