What is the difference between metaClass.methods and metaClass.metaMethods methods?

If I add a meta method to the class, I expect it to appear in Class.metaClass.metaMethods. But this does not seem to be the case. In particular, if I do this:

class Example {
    def realFoo() { "foo" }

}
Example.metaClass.metaFoo = { -> "foo" }

def reals = Example.metaClass.methods*.name.grep{it.contains("Foo")}
def metas = Example.metaClass.metaMethods*.name.grep{it.contains("Foo")}

println "reals = $reals, metas = $metas"

I would expect a conclusion reals = [realFoo], metas = [metaFoo], but actually get it reals = [realFoo, metaFoo], metas = [].

It appears that new meta methods are stored in methods, not metaMethods. So what is the difference between metaClass.methodsand metaClass.metaMethods?

+5
source share
1 answer

MetaMethods contains those methods that are decorated with the class using Groovy, but are not actually part of the class or inheritance structure, or which were manually inserted into the class via metaClass.

DefaultGroovyMethods.

, , , , , ..

, , "" :

class Example {
    def realFoo() { "foo" }

}
Example.metaClass.metaFoo = { -> "foo" }

def reals = Example.metaClass.methods.name.sort().unique()
def metas = Example.metaClass.metaMethods.name.sort().unique()

def metaOnly = metas - reals
def realOnly = reals - metas
def shared = reals.findAll { metas.contains(it) }

println """
metaOnly = $metaOnly
realOnly = $realOnly
shared = $shared
"""

:

metaOnly = [addShutdownHook, any, asBoolean, asType, collect, dump, each, eachWithIndex, every, find, findAll, findIndexOf, findIndexValues, findLastIndexOf, findResult, getAt, getMetaPropertyValues, getProperties, grep, hasProperty, identity, inject, inspect, is, isCase, iterator, metaClass, print, printf, println, putAt, respondsTo, sleep, split, sprintf, use, with]
realOnly = [equals, getClass, getProperty, hashCode, metaFoo, notify, notifyAll, realFoo, setProperty, wait]
shared = [getMetaClass, invokeMethod, setMetaClass, toString]

metaOnly shared DefaultGroovyMethods. "" (Object ), groovy , metaClass, / metaClass, getProperty/setProperty invokeMethod, .

, , , - :

def allMethods = (Example.metaClass.methods + Example.metaClass.metaMethods).name.sort().unique() 
+6
source

All Articles