This article is a summary of the experience of using Java reflection in the work, but also can be said to be some tips, learn new tricks, will be constantly updated. This article is not prepared to discuss the Java reflection mechanism, there are a lot of online, you can just google it.
Before I start, I'll define a test class student, and the code is as follows:
[Java] View plain copy package chb.test.reflect; public class student { private int age; private string name; public int getage () { return age; } public void setage (int age) { this.age = age; } public string getname () { return name; } Public void setname (string name) { this.name = name; } public static void hi (int age,string name) { system.out.println ("Hello, my name is +name+", this year "+age+"); } }<pre></pre>
general steps for using Java reflection
Reflection invocation is generally divided into 3 steps: Get the class you want to call the class to get the method call (methods) method invocation (Invoke)
code example:
[Csharp] view plain copy Class cls = Class.forName ("chb.test.reflect.Student"); Method m = Cls.getdeclaredmethod ("Hi", New Class[]{int.class,string.class}); M.invoke (Cls.newinstance (), "ChB");<pre></pre>
the type of the parameter in the method call
In a method call, the parameter type must be correct, and it is important to note that you cannot replace the base type with a wrapper class, such as Integer.class instead of Int.class.
If I want to call the student Setage method, the following call is correct:
[Java] view plain copy Class cls = Class.forName ("chb.test.reflect.Student"); Method Setmethod = Cls.getdeclaredmethod ("Setage", Int.class); Setmethod.invoke (Cls.newinstance ());<pre></pre>
And if we replace Int.class with Integer.class, we will make mistakes, such as:
[Java] view plain copy Class cls = Class.forName ("chb.test.reflect.Student"); Method Setmethod = Cls.getdeclaredmethod ("Setage", Integer.class); Setmethod.invoke (Cls.newinstance ());<pre></pre>
The JVM will report the following exception: [HTML] view plain copy java.lang.nosuchmethodexception:c