What function does reflection in java provide?
This article mainly explains "what function does reflection in java provide?" the content in the article is simple and clear, and it is easy to learn and understand. Please follow the editor's train of thought to study and learn "what function does reflection in java provide?"
1. Description
Determine the class to which any object belongs at run time
Construct an object of any class at run time
Determine the member variables and methods of any class at run time
Get generic information at run time
Call member variables and methods of any object at run time
Processing annotations at run time
Generate dynamic proxy
2. Examples
@ Testpublic void test1 () throws Exception {Class clazz = Person.class; / / 1. Through reflection, create the Person class object Constructor cons = clazz.getConstructor (String.class, int.class); Person person = cons.newInstance ("Tom", 12); System.out.println (person); / / Person {name='Tom', age=12} / / 2. Through reflection, call the property specified by the object, method / call property Field age= clazz.getDeclaredField ("age"); age.setAccessible (true); age.set (person, 10); System.out.println (person.toString ()); / / Person {name='Tom', age=10} / / call method Method show = clazz.getDeclaredMethod ("show"); show.invoke (person) / / my name is Tom and age is 10 System.out.println ("="); / / through reflection, you can call the private structure of the Person class. For example, private constructors, methods, properties / / calls private constructors Constructor cons1 = clazz.getDeclaredConstructor (String.class); cons1.setAccessible (true); Person p1 = cons1.newInstance ("Bruce"); System.out.println (p1); / / Person {name='Bruce', age=0} / / calls private properties Field name= clazz.getDeclaredField ("name"); name.setAccessible (true) Name.set (p1, "Jarry"); System.out.println (p1); / / call the private method Method nation = clazz.getDeclaredMethod ("nation", String.class); nation.setAccessible (true); Object nation1 = (String) nation.invoke (p1, "China"); / / equivalent to String nation = p1.showNation ("China") System.out.println (nation1) / / I come from China} Thank you for your reading. The above is the content of "what function does reflection in java provide?" after the study of this article, I believe you have a deeper understanding of what function reflection in java provides, and the specific use needs to be verified in practice. Here is, the editor will push for you more related knowledge points of the article, welcome to follow!