The reflection mechanism is a special feature of the Java language. It can call methods and attributes in other classes in the class. This feature can be easily used in a self-developed framework. It can be said that the feature is quite powerful.
Create a new Java project. The directory structure is as follows:
Reflect class
package com.org.testReflect;public class Reflect {public String str="123456";public void print(){System.out.println("test ====================print");}public void printStr(String str){System.out.println("the param is================"+str);}public static void main(String[] args) {System.out.println("beging test main method----------------------");}}
Testref is a test class of reflect.
1. Obtain a simple method of methods and attributes in a class.
1. Obtain the instance of this class
Class ref = Class.forName("com.org.testReflect.Reflect");
Reflect obj = (Reflect)ref.newInstance();
2. Obtain attributes and methods in reflect
Using the newinstance method, we have a new reflect class. This method is equivalent
Reflect refs=new Reflect();
Therefore, you only need to use ref. To obtain the methods and attributes in this class. Some may ask why it takes so much effort to create a new class, what if I use the package names of the reflect classes to get the class instances through Java reflection? This is very simple. In some cases, we need to dynamically update a class instead of a specific class. At this time, Java reflection will come in handy. For example, when writing a framework, we may instance a Class Based on the configuration attributes in XML, because the attributes in XML are changed, so the classes of the instance are also changing, so direct new is not acceptable.
(1) Obtain a method without Parameters
obj.print();
(2) Obtain methods with Parameters
obj.printStr("1234");
(3) obtain the main method
obj.main(args);
(4) Get attributes
Reflect obj = (Reflect)ref.newInstance();System.out.println("================="+obj.str);
Code of this class
Package com.org. testreflect; public class testref {public static void main (string [] ARGs) {try {reflect refs = new reflect (); Class ref = Class. forname ("com.org. testreflect. reflect "); // reflect. class. getname () // method without parameters reflect OBJ = (reflect) ref. newinstance (); obj. print (); obj. printstr ("1234"); obj. main (ARGs); system. out. println ("========================" + obj. str);} catch (classnotfoundexception 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 ();}}}
The execution result is as follows:
test ====================printthe param is================1234beging test main method----------------------=================123456
We can see that the reflect class is fully entered. And obtain the methods and attributes in the table,
2. Another method of reflection mechanism
The above provides a method to obtain the method in other classes. Here we provide another method.
1. Load the class to be called
Class ref = Class.forName(Reflect.class.getName());
2. Call Method
You can call a method in two steps.
A. Obtain the method to be called.
Method method=ref.getMethod(name, parameterTypes)
The first parameter is the name of the method to be called, and the second parameter represents the type of the parameter in the method.
B. Call Methods
method.invoke(obj, args)
The first parameter is an instance of class. If it is null, it indicates that the method is static, and the second parameter is the parameter value to be passed in. OBJ can be obtained using the following method:
Object obj = ref.newInstance();
The following describes how to call common methods.
(1) Main Method
Method method = ref.getMethod("main", String[].class);method.invoke(null,(Object)new String[]{});
(2) No Parameter Method
Method mf=ref.getMethod("print", null);mf.invoke(obj, null);
(3) methods with Parameters
Method m=ref.getMethod("printStr", String.class);m.invoke(obj, new String("asdf"));
Running result
the param is================asdftest ====================printbeging test main method----------------------
Iii. classes with Constructors
The two methods mentioned above are non-constructor classes. If there is a constructor, the above two methods will no longer apply.
Let's start to build a new Java class reflect2.java Code as follows:
package com.org.testReflect;public class Reflect2 {public Reflect2(String str) {// TODO Auto-generated constructor stubSystem.out.println("constructor begining run param str is============="+str);}public void print(){System.out.println("test ====================print");}public void printStr(String str){System.out.println("the param is================"+str);}public static void main(String[] args) {System.out.println("beging test main method----------------------");}}
Create a new Java class testref2.java for test reflection
For classes with constructors, use
ref.newInstance();
An error will be reported. If you are interested, you can test it and see what the error is.
Here, we can instantiate this class by following the steps below
1. Get the constructor
Constructor<?>[] ref = Class.forName("com.org.testReflect.Reflect2").getConstructors();
2. instantiation class
Object obj = ref[0].newInstance(new String("qaz"));
3. After obtaining the OBJ instance, you can call it according to the second method. The test results are as follows:
constructor begining run param str is=============qaztest ====================printthe param is================printString=========1234beging test main method----------------------