Reflection (reflection) is regarded as the key dynamic languages,
reflection by means of the Reflection API allows a program in the execution of any type of internal information acquired,
and the internal property and a method of operation of any object can be directly
package com.aff.reflection; import java.lang.reflect.Field; import java.lang.reflect.Method; import org.junit.Test; /* Reflection (reflection) is regarded as the key to dynamic languages, Reflection Reflection API allows a program to make any type of internal information by means of the implementation period, And can directly operate any internal object properties and methods Java reflection mechanism provides functionality: ① any one object belongs to the class determined at runtime ② a configuration of objects of any class at runtime ③ determining any class has member variables and methods at runtime ④ to call any member variables and methods of an object at runtime ⑤ generate dynamic proxy Reflecting mainly related API: ① java.lang.Class: on behalf of a class ②java.lang.reflect.Method: method represents a class of Field representing the class: ③java.lang.reflect.Field ④java.lang.reflect.Constructor: Representative class constructor 。。。 */ public class TestReflection { // With reflective, can be created by a reflecting object class and invoke a configuration @Test public void test2 () throws Exception { Class . <Person> = clazz Person class ; // 1. Create clazz Person class corresponding runtime class Person P = clazz.newInstance (); System.out.println(p);// Person [name=null, age=0] // specified attribute when invoked by reflection 2. Run class // attributes 2.1public of Field, F1 = clazz.getField ( "name" ); f1.set (P, "Bai" ); System.out.println(p);// Person [name=李白, age=0] // 2.2private 的属性 使用getDeclaredField ,setAccessible(true) Field f2 = clazz.getDeclaredField("age"); f2.setAccessible(true); f2.set(p, 33); System.out.println(p);// Person [name=李白, age=33] // specified 3. Run class when invoked by reflection Method, M1 = clazz.getMethod ( "Show" ); m1.invoke (the p-); // can be followed, then remove with no parameters, namely singing was lost, ie Hugh Method, M2 = clazz.getMethod ( "Run the display", String. class ); // <?> Class ... parameterTypes ,
// class should write the type of m2.invoke (p, "Luo Yin"); // a worry also hate the lengthy \ n Luo Yin } // In the previous reflection mechanism, how to create a class of objects and invoke methods, properties @Test public void test1 () { Person p = new Person(); p.setAge(35); p.setName("罗隐"); System.out.println(p); p.show(); p.display ( "Late Tang" ); } }