gpt4 book ai didi

groovy - Groovy 的 MetaClass 有什么用?

转载 作者:行者123 更新时间:2023-12-03 11:48:42 25 4
gpt4 key购买 nike

Groovy 和其他 OO 编程语言中的 Meta-Class 有什么用?

最佳答案

您可能会想到 Groovy's MetaClass :

A MetaClass within Groovy defines the behaviour of any given Groovy or Java class. The MetaClass interface defines two parts. The client API, which is defined via the extend MetaObjectProtocol interface and the contract with the Groovy runtime system. In general the compiler and Groovy runtime engine interact with methods on this class whilst MetaClass clients interact with the method defined by the MetaObjectProtocol interface



Groovy MetaClass 允许您在运行时将行为和状态分配给类,而无需编辑原始源代码,它是原始类之上的一层。

这是 Groovy 用于 extend the Java JDK objects 的机制.

示例:
Object.class.metaClass.explode{-> println "Boom! ${delegate} Exploded!"}
"SomeString".explode();
12345.explode();

输出:

Boom! SomeString Exploded!
Boom! 12345 Exploded!



有关更高级的用法,请阅读: MetaClasses

关于groovy - Groovy 的 MetaClass 有什么用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5340189/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com