Adding a method to the metaclass interface only works once

Thus, adding a method to the metaClass interface adds it to all instances of the interface implementations - but only once. Adding a method to each executing class is performed every time for a change.

Clearing a metaclass between reassigning a method does not change anything.

Here is an example of execution:

interface X {}
class A implements X {}
class B implements X {}

X.metaClass.test = { println "v1" }
new A().test()
new B().test()

X.metaClass.test = { println "v2" }
new A().test()
new B().test()

A.metaClass.test = { println "v3" }
B.metaClass.test = { println "v3" }

new A().test()
new B().test()

A.metaClass.test = { println "v4" }
B.metaClass.test = { println "v4" }

new A().test()
new B().test()

and the result:

v1
v1
v1
v1
v3
v3
v4
v4

Is this the intended behavior? If so, why? Or is it a mistake?

+4
source share
1 answer

, , (GROOVY-3493). , , , , metaClass. .

, , metaClass, , . metaClass , . metaClass , .

, , , ; , metaClass , ():

โ€‹interface X {}
class A implements X {} 
class B implements X {}  

X.metaClass.test = { println "v1" } 

new A().test() 
new B().test()  

X.metaClass.test = { println "v2" } 
A.metaClass.test = { println "v2" }

new A().test() // Will print "v2"
new B().test()โ€‹ // Will print "v1" still
+2

Source: https://habr.com/ru/post/1673252/


All Articles