About Reflection:
1. Need to understand the loading mechanism of the JVM class (detailed in the Java Advanced section)
2. Reflected API in fact, as long as more look at the API and source code, it is easy to understand.
Here is the code, which simply explains the use of reflection:
ImportJava.lang.reflect.Constructor;ImportJava.lang.reflect.Field;ImportJava.lang.reflect.Method;/*** Java Reflection mechanism (first for reflection, it is recommended to look at the Javaapi, to understand the source code, so as to better understand the principle of reflection, and can be used in the work well) * Definition: * Java reflection Mechanism is in the running state, for any of the classes, Can know all the properties and methods of this class, and for any object, it can call any of its methods and properties; * This dynamically acquired information and the ability to dynamically invoke the object's methods are called the Java language's reflection mechanism. * @authorDyq **/ Public classReflextest { Public Static voidMain (string[] args) {Try { /*** Returns a run-time class object*/Class<?> classanimal = Class.forName ("Cn.review.day03.entity.Animal"); /*** Create a new instance of the class represented by this class object*/Object Object=classanimal.newinstance (); /*** Get all construction methods*/Constructor<?>[] Constructors =classanimal.getconstructors (); for(inti=0;i<constructors.length;i++) {System.out.println (constructors[i]); } /*** Gets the method in the class object and calls the method*/Classanimal.getmethod ("SetName", String.class). Invoke (object, "Elephant")); Classanimal.getmethod ("Setaddress", String.class). Invoke (object, "Beijing"); Classanimal.getmethod ("SetCount",int.class). Invoke (Object, 20); Method Method= Classanimal.getmethod ("getmystring"); System.out.println (String) Method.invoke (object)); /*** Get common attribute method GetFields * Get private Property Method Getdeclaredfields*/field[] fields=Classanimal.getdeclaredfields (); for(inti=0;i<fields.length;i++) {Field field=Fields[i]; System.out.println (field); } } Catch(Exception e) {e.printstacktrace (); } }}
Java Basic Part review (V, Java reflection)