Java reflection mechanism (I) -- instantiate an object using the reflection mechanism
I. Java has a very prominent Dynamic correlation mechanism: Reflection, used in Java, refers to classes that we can load, explore, and use completely unknown during runtime compilation. In other words, a Java program can load a class whose name is known only at runtime, and learn its complete structure (but does not include the definition of methods ), and generate its object entity, set its fields value, or arouse its methods. (That's what du Niang library says)
II. This article mainly introduces how to instantiate a class object through the reflection mechanism and then call its method. This article mainly introduces two methods: the first is to instantiate through the constructor, and the second is to use the Class The newnstance () method of the class is instantiated. The following code is used:
1. First, I created a Person class for testing:
Package com. reflect. test;/*** @ author Lin Xiaopeng * @ description for testing * @ create 2014-11-27 9:34:00 */public class Person {private int age; private String name; public Person () {} public Person (String name) {this. name = name;} public Person (int age, String name) {this. age = age; this. name = name;} public void setAge (int age) {this. age = age;} public void setName (String name) {this. name = name;} public int getAge () {return age;} public String getName () {return name ;}}
2. constructor:
Package com. reflect. test; import java. lang. reflect. constructor; import java. lang. reflect. invocationTargetException; import java. lang. reflect. method;/*** @ author Lin Xiaopeng * @ description reflection mechanism, instantiate the object through the constructor * @ create 9:32:05 **/public class ReflectConstructor {public static void main (String [] args) {Person person Person = new Person (); try {Class
Cls = Class. forName (person. getClass (). getName (); // parameter type Class
[] Params = {Integer. TYPE, String. class}; // parameter value Object [] values = {15, "kroc"}; // Constructor with two parameters
Constructor = cls. getDeclaredConstructor (params); // generate Instance Object = constructor based on the input value of the constructor according to the constructor. newInstance (values); Method getAge = cls. getDeclaredMethod ("getAge"); Method getName = cls. getDeclaredMethod ("getName"); System. out. println ("getAge =" + (Integer) getAge. invoke (object); System. out. println ("getName =" + (String) getName. invoke (object);} catch (ClassNotFoundException e) {e. printStackTrace (); System. out. println ("ClassNotFoundException");} catch (NoSuchMethodException e) {// TODO Auto-generated catch blocke. printStackTrace ();} catch (SecurityException e) {// TODO Auto-generated catch blocke. printStackTrace ();} catch (InstantiationException e) {// TODO Auto-generated catch blocke. printStackTrace ();} catch (IllegalAccessException e) {// TODO Auto-generated catch blocke. printStackTrace ();} catch (IllegalArgumentException e) {// TODO Auto-generated catch blocke. printStackTrace ();} catch (InvocationTargetException e) {// TODO Auto-generated catch blocke. printStackTrace ();}}}
We can see that the following two lines in the Code are important. The first line is to obtain a constructor through the number of parameters, remember that the number and type of parameters passed here must be consistent with those in the constructor in Person, and the parameter type must be the same as that of the parameter value values, in this example, params and values are encapsulated and passed together.
// Constructor
Constructor = cls. getDeclaredConstructor (params); // generate an instance Object object = constructor. newInstance (values) based on the input value of the constructor according to the constrfunction );
The running result is as follows:
3. The second method is to use the Class Class newnstance () method initialization:
Package com. reflect. test; import java. lang. reflect. invocationTargetException; import java. lang. reflect. method;/*** @ author Lin Xiaopeng * @ description reflection mechanism, through newInstance () instantiate object * @ create 9:41:01 */public class ReflectMethod {public static void main (String [] args) {Person person = new Person (); try {Class
Cls = Class. forName (person. getClass (). getName (); // generates an instance. By default, the Object object = cls is called. newInstance (); Method setName = cls. getDeclaredMethod ("setName", String. class); Method setAge = cls. getDeclaredMethod ("setAge", Integer. TYPE); setName. invoke (object, "KrocLin"); setAge. invoke (object, 20); Method getAge = cls. getDeclaredMethod ("getAge"); Method getName = cls. getDeclaredMethod ("getName"); System. out. println ("getAge =" + (Integer) getAge. invoke (object); System. out. println ("getName =" + (String) getName. invoke (object);} catch (ClassNotFoundException e) {e. printStackTrace (); System. out. println ("ClassNotFoundException");} catch (NoSuchMethodException e) {// TODO Auto-generated catch blocke. printStackTrace ();} catch (SecurityException e) {// TODO Auto-generated catch blocke. printStackTrace ();} catch (InstantiationException e) {// TODO Auto-generated catch blocke. printStackTrace ();} catch (IllegalAccessException e) {// TODO Auto-generated catch blocke. printStackTrace ();} catch (IllegalArgumentException e) {// TODO Auto-generated catch blocke. printStackTrace ();} catch (InvocationTargetException e) {// TODO Auto-generated catch blocke. printStackTrace ();}}}
The code can understand that in fact, newInstance () is used to call the default no-argument constructor of Person, so it is essentially the same as the previous method.
Running result:
3. There are still many things that can be done with the reflection mechanism. For simple display, the names of methods like getName are all written to death. In fact, the method names can also be obtained through reflection, including the return type of methods and thrown exceptions, which can be obtained through the reflection mechanism. I will write more articles about the java reflection mechanism in the future. I 'd like to comment on this article if I have made a mistake or have any better suggestions.