In the Java environment, the reflection mechanism allows a program to obtain a variety of its own definition information, such as properties and methods, that can also implement the ability to dynamically create objects of a class, change the contents of a property, or perform a specific method. So that Java has dynamic language characteristics, enhance the flexibility and portability of the program.
the function of the reflection mechanism:
1. At runtime, determine the type of any object to which it belongs;
2. Constructs an object of any class at run time;
3. Judge the member variables and methods of any class at run time;
4. Call a method of any object at run time, or even invoke the private method.
Java Reflection mechanism API:
The API that implements the Java reflection mechanism has a few points under the Java.lang.reflect package:
1.Class class: Representing a class;
2.Field class: Representing the member variables of the class;
3.Method class: Method of representing class;
4.Constructor class: Represents the construction method of class;
5.Array class: Provides a static method for dynamically creating arrays and accessing elements of an array. All methods in the class are static.
Sample code One:
/* Print out all the properties and methods of the String class */public
void Test () {
Class C = String.class;
Method[] methods = C.getmethods ();
for (int i=0;i<methods.length;i++) {
System.out.println (methods[i].getname);
}
fields[] Fields = C.getfields ()
for (Field f:fields) {
System.out.println (F.gettype () + "," +f.getname ());
}
}
Example two:
/* Dynamically create object based on class name/public
void Test () {
Class C = Class.forName ("Student");
Student Student = (Student) c.newinstance ();
Student.setname ("Tom");
Student.setage (ten);
SYSTEM.OUT.PRINTLN (student);
Override ToString () method
}
Example three:
/* Dynamically create array objects, assign values and values for arrays/public
void Test () {
Class c = class.forname ("java.lang.String");
Create a String type array,the length is ten
Object arr = array.newinstance (c,10);
At the index =5, assignment the parameter value
array.set (arr,5, "It is a Test");
Get the index=5 value
String s = (string) array.get (arr,5);
System.out.println (s);
}
Click to see reflection for detailed reference