Background: Today in the project to use the method of the Invoke methods, but do not understand, check out just know, so!
ImportJava.lang.reflect.Method; /*** Java.lang.reflect.Method Invoke Method instance * There is a description of the Get,set method of the entity object in the configuration file in the program, and calling the entity object by applying the Invoke () method return * M_oget Ter.invoke (OSRC, NULL); OSRC is the Entity object, Method M_ogetter * Here M_ogetter is the method instance corresponding to the interface methods that are called on the proxy instance (OSRC), as shown in the example code below **/ 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; } Public classInvokemethods { Public Static voidMain (string[] args) {Employee emp=NewEmployee (); Class<?> cl =Emp.getclass (); ///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 }); Method GAge= Cl.getmethod ("Getage",NULL); Method PName= Cl.getmethod ("Printname", NewClass[] {String.class }); /*** Invoke the specified method using invoke*/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); } }
Operation Result:
The Employee Age is:25
The Employee Name is:jack
Go Java.lang.reflect.Method Invoke Method Instance