Take advantage of reflection. In use inside
Method.invoke (tool, null); The method inside the tool can be called
1 Public classTool {2 3 Public voidA ()///Method A4 {5System.out.print ("TOOL.A () ...");6 }7 8 Public voidB ()//Method B9 {TenSystem.out.print ("tool.b () ..."); One } A } - - the - - Public classControl { - Public voidInvokeintflag) { +User User =NewUser (); - Try { + Switch(flag) { A Case0: atUser.use (Tool.class. GetMethod ("a",NULL)); - Break; - default: -User.use (Tool.class. GetMethod ("B",NULL)); - Break; - } in}Catch(Exception e) { - e.printstacktrace (); to } + - } the } * $ Panax Notoginseng - the + A the ImportJava.lang.reflect.Method; + - Public classUser $ { $ Public voidUse (method) - { -Tool tool =NewTool (); the Try { -<span style= "color: #FF0000;" >method.invoke (Tool,NULL);</span>Wuyi}Catch(Exception e) { the e.printstacktrace (); - } Wu } - About Public Static voidMain (string[] args) { $Control control =NewControl (); -Control.Invoke (0); - } -}
Java passes the function as a parameter