There are student classes:
Package Testreflection;public class Student{private static int count;private string Stunum;public Student (String stunum) {//TODO auto-generated constructor stubthis.stunum = stunum;count++;} Public String Getstunum () {return stunum;} public void Setstunum (String stunum) {this.stunum = Stunum;} public static int GetCount () {return count;}}
The test code that uses reflection to invoke the method of the student class is as follows:
Package Testreflection;import Java.lang.reflect.invocationtargetexception;import Java.lang.reflect.method;public Class TestMethod {public static void main (string[] args) {//TODO auto-generated method stubtry {Student Student = new Stu Dent ("20101120244"); the method signature of/** * GetMethod is as follows: * GetMethod (String name, Class<?> .... parametertypes), * The first parameter is the method name, The next parameter is the parameter list of the method to be called type * Corresponding Class object */method m1 = Student.getclass (). GetMethod ("Getstunum"); the method signature for/** * Invoke is as follows: * Invoke (Object obj, Object ... args), * The first parameter is the object to which the method belongs, and if it is a static method, set to NULL, * the next parameter is the parameter */system.out.println to be passed to the method to be called (M1.invoke ( Student)); Method m2 = Student.getclass (). GetMethod ("Setstunum", String.class); M2.invoke (student, "20121120064"); System.out.println (M1.invoke (student)); Method m3 = Student.class.getMethod ("GetCount"); SYSTEM.OUT.PRINTLN (M3.invoke (null));} catch (Nosuchmethodexception e) {//TODO auto-generated catch Blocke.printstacktrace ();} catch (SecurityException e) {//T ODO 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 results of the operation are as follows:
20101120244
20121120064
1
It is worth mentioning that I have not been able to use reflection to access the private method of the class, this sentence
Setaccessible (TRUE);
It's not good to use.
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Java Reflection (iii) invoking methods with reflection