简体   繁体   English

groovy中方法调用按什么顺序进行?

[英]In which sequence does method call work in groovy?

I am using groovy 2.3.8 我正在使用groovy 2.3.8

I am trying to figure out how method calls work in groovy. 我试图弄清楚方法调用在groovy中是如何工作的。 Specifically if we have a Java class hierarchy each having a metaClass like below 具体来说,如果我们有一个Java类层次结构,每个层次结构都有一个metaClass如下所示

class A {
}
A.metaClass.hello = {
  "hello superclass"
}

class B extends A {
}
B.metaClass.hello = {
  "hello subclass"
}

If I use new B().hello() I get hello subclass . 如果我使用new B().hello()我会得到hello subclass If I remove meta class of B then I get hello superclass . 如果我删除B的元类,那么我会hello superclass

Based on changing the above example I think groovy goes in the below sequence to find which method to call 基于更改上面的示例,我认为groovy按照以下顺序查找要调用的方法

method-in-subclass's-metaclass ?: subclass-metho  ?: method-in-superclass's metaclass ?: method-in-superclass

So how does groovy lookup which method to call? 那么groovy如何查找要调用的方法?

Well, the hierarchy is the expected object oriented programming method overloading, which is what you witnessed. 好吧,层次结构就是预期的面向对象的编程方法重载,这就是您所看到的。 What differs is the dispatching. 区别在于调度。 Instead of starting with a method lookup in instance's class, it begins with the MOP (meta object protocol). 它不是从实例类中的方法查找开始,而是以MOP (元对象协议)开始。

In layman's terms, because the MOP is programmable, so is the way methods are invoked :) 用外行的话来说,因为MOP是可编程的,所以方法的调用方式也是:)

How it works 这个怎么运作

The following diagram from Groovy's documentation shows how methods are looked up. Groovy 文档中的下图显示了如何查找方法。

Groovy对象的Groovy方法分派

What's not clear in the diagram is that there's an instance metaclass as well, and it comes before the class's metaclass. 在图中不清楚的是,还有一个实例元类,它在该类的元类之前。

Something that may help is looking at an object's or class's .metaClass.methods Methods added through inheritance, traits, metaclass, etc are listed in a flat list. 可能有帮助的是查看对象或类的.metaClass.methods在继承列表中列出了通过继承,特征,元类等添加的方法。 The inheritance hierarchy is flattened. 继承层次结构被展平。 .metaClass.metaMethods on the other hand seems to contain methods added via the GDK. 另一方面, .metaClass.metaMethods似乎包含通过GDK添加的方法。 From the list I could not tell method precedence :( 从列表中我不能告诉方法优先级:(

Based on observation, the rule seems to be this: the last MetaClass standing wins. 根据观察,规则似乎是这样的:最后一个MetaClass获胜。

class A { }

class B extends A { }

A.metaClass.hello = {
  "hello superclass"
}

B.metaClass.hello = {
  "hello subclass"
}

def b = new B()

assert b.hello() ==  "hello subclass"
b.metaClass = A.metaClass
assert b.hello() ==  "hello superclass"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM