JAVA基础:invokeMethod和methodMissing方法
来源:优易学  2011-10-8 11:01:40   【优易学:中国教育考试门户网】   资料下载   IT书店
  对于“invokeMethod”方法,大家一定很熟悉了,我们可以用下面一个简单的例子来看看它的作用:
  class InvokeTestor1 {
  def hello()
  {
  'invoke hello directly'
  }
  def invokeMethod(String name,Object args)
  {
  return "unknown method $name(${args.join(',')})"
  }
  static void main(args) {
  def it = new InvokeTestor1()
  println it.hello()
  println it.foo("mark",19)
  }
  }
  运行的结果为:
  invoke hello directly
  unknown method foo(mark,19)
  可以看出,对于一个对象的方法调用来说,如果这个方法能够被分派出去,如上面的“hello”方法,可以在InvokeTestor1类中找到,就被分派给InvokeTestor1类的“hello”方法;如果不能被分派,如上面的“foo”方法,则调用“invokeMethod”方法。
  在Groovy语言中,还有一个方法也可以实现上面的功能,这就是“methodMissing”方法,请看下面的例子:
  class MethodTestor1 {
  def hello()
  { "invoke hello directly"
  }
  def methodMissing(String name,args)
  {
  return "unknown method $name(${args.join(',')})"
  }
  static void main(args) {
  def mt = new MethodTestor1()
  println mt.hello()
  println mt.foo('mark',19)
  }
  }
  我们还是来看看上面的代码的运行结果:
  invoke hello directly
  unknown method foo(mark,19)
  Examda提示: 可以看到,“methodMissing”方法就像它的名字一样,如果方法可以在类中找得到,那么就调用该方法;如果找不到,那么就是“missing method”,就可以调用“methodMissing”方法了。跟“invokeMethod”功能非常类似。
  这点大家都清楚,但实际上,“invokeMethod”在Groovy语言中是用来分派一个对象的所有方法的。要做到这一点,就需要借助于“GroovyInterceptable”接口。请看下面的例子:
  class InvokeTestor2 implements GroovyInterceptable{
  def hello()
  {
  "invoke hello directly"
  }
  def invokeMethod(String name,Object args)
  {
  return "unknown method $name(${args.join(',')})"
  }
  static void main(args) {
  def it = new InvokeTestor2()
  println it.hello()
  println it.foo('mark',19)
  }
  }
  运行结果为:
  unknown method hello()
  unknown method foo(mark,19)
  从运行结果可以看出,“invokeMethod”方法的确可以分派所有的方法,只要我们实现“GroovyInterceptable”接口即可。
  而“methodMissing”方法呢,即使类实现了“GroovyInterceptable”接口,它也不能使用“methodMissing”方法来分派所有的方法。请看下面的例子:
  class MethodTestor2 implements GroovyInterceptable{
  def hello()
  {
  "invoke hello directly"
  }
  def methodMissing(String name,args)
  {
  return "unknown method $name(${args.join(',')})"
  }
  static void main(args) {
  def mt = new MethodTestor2()
  println mt.hello()
  println mt.foo('mark',19)
  }
  }
  Examda提示它的运行结果为:
  invoke hello directly
  unknown method foo(mark,19)
  通过了上面的比较,我们可以看出“invokeMethod”方法和“methodMissing”方法的微妙区别:即,“invokeMethod”方法可以分派所有的方法,包括一个类已经实现了的和未实现的方法;而它实现上面的功能是通过这个类实现“GroovyInterceptable”接口达到的。而“methodMissing”方法则只能分派一个类未实现的方法,无论它是否实现了“GroovyInterceptable”接口。
  这种区别的确很微妙,如果我们想让一个方法来管理一个类所有方法的调用,那么我们必须使用“invokeMethod”方法;如果我们只想通过一个方法来管理一个类的所有“missing method”,即不能被分派出去的方法,那么使用“methodMissing”方法是比较有效的;当然,“invokeMethod”方法也能实现“methodMissing”方法的功能。

责任编辑:小草

文章搜索:
 相关文章
热点资讯
资讯快报
热门课程培训