Groovy - add a property or method dynamically to this metaClass

I want to dynamically add field and methods to metaClassmy current object. I tried

this.metaClass.testProp = "test"

to add a field called testProp. However i get

groovy.lang.MissingPropertyException: No such property: testProp for class: groovy.lang.MetaClassImpl

When I do the same thing at the class level, for example. adding testProp to the class, not directly to the object

Process.metaClass.testProp = "test"

it works, but my object does NOT inherit the field. Any ideas or pointers in the right direction would be very helpful.

+4
source share
1 answer

Short answer:

Process.metaClass.testProp = "test"
this.metaClass = null
assert this.testProp == "test"

Long answer:

, 3 , . , . -, Groovy ( Groovy). , - .

, , - , , ExpandoMetaClass (EMC), . met , . - . Process.metaClass.testProp = "test" . , -, , , . this.metaClass.testProp = "test" - , . this.metaclass = null reset. . , . , .

, Groovy (MetaClassImpl). , - ExpandoMetaClass (EMC). , . , ExpandoMetaClass , - , : ExpandoMetaClass.enableGlobally()

, ,

Process.metaClass.testProp = "test"
this.metaClass = null
assert this.testProp == "test"

ExpandoMetaClass.enableGlobally() - , reset ( - , "this"), EMC). , Grails EMC

+6

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


All Articles