First, take a look at the concept of reflection:
The Java reflection mechanism is in the running state, and for any class, all the properties and methods of the class are known, and any one of its methods can be invoked for any object, and this dynamically acquired information and the function of the method that dynamically invokes the object are called the reflection mechanism of the Java language.
The Java reflection mechanism mainly provides the following features: To determine at run time the class to which any object belongs, to construct an object of any class at run time, to determine the member variables and methods of any class at run time, to invoke a method of any object at run time, and to generate a dynamic proxy.
Second, the function of the reflection mechanism:
1, decompile:. Class-->.java
2, through the reflection mechanism to access the Java object properties, methods, construction methods, etc.
This seems to be easier to understand, and we'll see how we can implement these features below.
Three, let's look at what Sun has provided us with the classes in the reflection mechanism:
Java.lang.Class;
Java.lang.reflect.Constructor; Java.lang.reflect.Field;
Java.lang.reflect.Method;
Java.lang.reflect.Modifier;
Many of the methods in reflection, attributes, and so on can be queried from these four classes. or which sentence to learn the constant query API, that is our best teacher.
Four, the concrete function realizes:
1, the reflection mechanism obtains the class to have three kinds of methods, we obtain the employee type
[Java] view plain copy print? The first way: CLASSC1 = Class.forName ("Employee"); The second way: each type in//java has a class attribute. CLASSC2 = Employee.class; The third way: Any Java object in the//java language has a getclass method employeee = new Employee (); CLASSC3 = E.getclass (); C3 is the Run-time class (The Run-time class of E is Employee)
2, create object: After getting the class we will create its object, using newinstance:
[Java] view plain copy print? Class c =class.forname ("Employee"); Creates a new instance of the class represented by this class object objecto = C.newinstance (); The parameterless constructor method for employee was invoked.
3, Get Properties: divided into all attributes and specified properties:
A, first look at getting all the attributes written:
[Java] View plain copy print? Get the whole class class c = class.forname ("Java.lang.Integer"); //get all the properties? field[] fs = c.getdeclaredfields (); //defines variable-length strings that are used to store properties stringbuffer sb = new stringbuffer (); //each attribute into this string by appending the method //the outermost public definition &Nbsp; sb.append (Modifier.tostring (C.getModifiers ()) + " class " + c.getsimplename () + "{\ n"); Each of the attributes inside the //