Invoke is used in the teacher's project to reflect the corresponding function by the function name. The code briefly introduces the Invoke method in Java reflection, and if you want to be specific, you can refer to the reflection part of the magic Core course.
PackageOrg.curry.tool;ImportJava.lang.reflect.Method; Public classInvokemethods { Public Static voidMain (string[] args) {Employee emp=NewEmployee (); Class CL= Emp.getclass ();//It's class, not class.///getclass Gets the object of the type to which the EMP object belongs, class is classes///class is a class specifically used to describe classes, such as those that describe a class with fields,///methods, constructors, etc.! Try { ///getmethod Method The first parameter specifies a method name that needs to be called///Here is the Setage method for the employee class, and the second argument is to call the//a list of parameter types for the method, which is the parameter type! Null if no parameter can be specified///The method returns a Method objectMethod SAge = Cl.getmethod ("Setage",NewClass[] {int.class});//The arguments must be the same as in the method int and integer,double and double are treated as different typesMethod GAge = Cl.getmethod ("Getage",NULL); Method PName= Cl.getmethod ("Printname", NewClass[] {String.class }); Object[] ARGS1= {NewInteger (25) }; //parameter list//an EMP is an implicit parameter that the method is not a static method must specifySage.invoke (EMP, ARGS1); Integer Age= (Integer) gage.invoke (EMP,NULL); intAge =Age.intvalue (); System.out.println ("The Employee Age is:" +Age ); Object[] ARGS3= {NewString ("Jack") }; Pname.invoke (EMP, ARGS3); } Catch(Exception e) {e.printstacktrace (); } system.exit (0); }}classEmployee {//define an employee class PublicEmployee () { age= 0; Name=NULL; } //the method that will be called Public voidSetage (inta) { age=A;} //the method that will be called Public intGetage () {returnAge ;} //the method that will be called Public voidPrintname (String N) {name=N; System.out.println ("The Employee Name is:" +name); } Private intAge ;PrivateString name;}
Reprinted from: http://blog.sina.com.cn/s/blog_64e467d60100yqz9.html
Reflection in Java, Invoke method [go]