Mechanism and implementation of method object
1, Method Object Overview
1) The Java.lang.reflect.Method class is the class used to represent the method object in the class, in the interface.
2) You can manipulate all methods, such as private and public, in the class.
2, method object of common methods introduction
| Method name |
Interpretation |
| GetName () |
Get Method Name |
| Getreturntype () |
Get method return value type |
| Invoke (Object obj, object ... args) |
Call this method with the Obj object |
| Getparametertypes () |
Get method all parameter types, return class array in order |
| Getdeclaredannotations () |
Get all annotations for a method |
PackageCom.rainmer.main;ImportJava.lang.reflect.Method;ImportJava.lang.reflect.Modifier;ImportCom.rainmer.bean.Book; Public classMethodtest {//This method is used to get all method names, return value types, and parameter information for an object Public voidShow (Object ob) {Class cl=Ob.getclass (); Method[] Me=Cl.getdeclaredmethods (); for(Method mm:me) {System.out.println ("Method Name:" +mm.getname ()); System.out.println ("Method modifier:" +modifier.tostring (Mm.getmodifiers ())); System.out.println ("Method return value type:" +Mm.getreturntype ()); Class[] Pretype=mm.getparametertypes (); System.out.println ("Method parameter list:"); for(Class cll:pretype) {System.out.println (Cll.getname ()); } } } //This method is used to get the method of the entity object passed over, and the pie call Public voidshowuse (Object ob) {Class cl=Ob.getclass (); Try{Method me= Cl.getmethod ("GetName",NULL); Me.invoke (ob,NewObject[0]);//invoke invokes, parameter is an object array of length 0Method me1= Cl.getmethod ("SetName", String.class); Me1.invoke (ob,"Journey to the Monkey");//the Ob object called the Me1 methodclass[] CLL= {String.class,int.class}; Method me2= Cl.getmethod ("Test", CLL); Object[] Obb= {"Hahaha", 12}; Me2.invoke (ob, OBB); } Catch(Exception e) {e.printstacktrace (); } } Public Static voidMain (string[] args) {book Bo=NewBook (); Bo.setid (1); Bo.setname ("The day I lived with Sister Feng"); Bo.settype (Thriller); Methodtest Test=Newmethodtest (); Test.showuse (BO); System.out.println (Bo.getname ()); }}
Operation Result:
Called the SetName method
Called the GetName method
Called the SetName method
A method that calls a multi-parameter
Called the GetName method
Journey
Introduction to the Java Reflection Mechanism 3