1. User Class
Packagecom.lf.entity;ImportCom.lf.annotation.SetProperty;Importcom.lf.annotation.SetTable; Public classuserentity {PrivateString UserName; Private intUserage; Private Final intMoney = 10000; PublicString GetUserName () {returnUserName; } Public voidsetusername (String userName) { This. UserName =UserName; } Public intGetuserage () {returnUserage; } Public voidSetuserage (intuserage) { This. Userage =Userage; } //How to borrow money Public intGetmoney () {System.out.println ("You borrowed" + Money + "Yuan! "); returnMoney ; } //still Money method, single parameter Public voidRepay (intMoney ) {System.out.println ("You have also" + Money + "Yuan! "); } //still Money method, multiple parameters Public voidRepay (String UserName,intMoney ) {System.out.println (UserName+ "also" + Money + "Yuan! "); }}
2. Test class
Packagecom.lf.test;ImportJava.lang.reflect.Method;Importcom.lf.entity.UserEntity; Public classReflection {//The reflection call method gets the return value//the first method, gets the object, calls the method directly through the object//the second method, obtained by means of the method name, executes the method Public Static voidMain (string[] args)throwsException {Class<?> userclass = Class.forName ("com.lf.entity.UserEntity"); Userentity userentity=(userentity) userclass.newinstance (); //The first of these methodsSystem.out.println ("The first time to borrow money:"); intMoney =Userentity.getmoney (); System.out.println ("Actually get the money for:" +Money ); System.out.println ("------------------------Split Line------------------------"); //the second method, (example of no argument: borrowing money)SYSTEM.OUT.PRINTLN ("Borrowing money for the second time:"); Method Getmoney= Userclass.getmethod ("Getmoney");//Get Method ObjectObject Money2 = Getmoney.invoke (userentity);//call the Borrowing method to get the return valueSystem.out.println ("Actually get the money for:" +Money2); System.out.println ("------------------------Split Line------------------------"); //the second method, (example of a single argument: Pay back)System.out.println ("The first time to pay back money:"); Method Repay1= Userclass.getmethod ("Repay",int.class);//to get the method object, the parameter type must be specifiedRepay1.invoke (userentity,3000);//Execute the Money method, have the referenceSystem.out.println ("------------------------Split Line------------------------"); //the second method, (example of a single argument: Pay back)System.out.println ("The second time Money:"); Method Repay2= Userclass.getmethod ("Repay", String.class,int.class);//to get the method object, the parameter type must be specifiedRepay2.invoke (userentity, "Xiao Fei", 5000);//Execute the Money method, have the reference }}
Java Reflection Call Method