Function Description
1. Determine the class to which any object belongs during operation.
2. Construct objects of any class at runtime.
3. Determine the member variables and methods of any class during operation.
4. Receive information during operation.
Call member variables and methods of any object at runtime.
Process comments at runtime.
Generate dynamic proxy.
Example
@Test public void test1() throws Exception { Classclazz = Person.class; //1.通过反射,创建Person类对象 Constructor cons = clazz.getConstructor(String.class, int.class); Person person = cons.newInstance("Tom", 12); System.out.println(person);//Person{name='Tom', age=12} //2.通过反射,调用对象指定的属性、方法 //调用属性 Field age = clazz.getDeclaredField("age"); age.setAccessible(true); age.set(person, 10); System.out.println(person.toString());//Person{name='Tom', age=10} //调用方法 Method show = clazz.getDeclaredMethod("show"); show.invoke(person);//my name is Tom and age is 10 System.out.println("==================================="); //通过反射,可以调用Person类的私有结构的。比如:私有的构造器、方法、属性 //调用私有的构造器 Constructor cons1 = clazz.getDeclaredConstructor(String.class); cons1.setAccessible(true); Person p1 = cons1.newInstance("Bruce"); System.out.println(p1);//Person{name='Bruce', age=0} //调用私有的属性 Field name = clazz.getDeclaredField("name"); name.setAccessible(true); name.set(p1, "Jarry"); System.out.println(p1); //调用私有的方法 Method nation = clazz.getDeclaredMethod("nation", String.class); nation.setAccessible(true); Object nation1 = (String) nation.invoke(p1, "China");//相当于String nation = p1.showNation("China") System.out.println(nation1);//I come from China }
The above is the detailed content of What are the functions of Java reflection mechanism?. For more information, please follow other related articles on the PHP Chinese website!