gpt4 book ai didi

groovy - groovy 如何为 Java 类添加新方法?

转载 作者:行者123 更新时间:2023-12-04 18:44:09 25 4
gpt4 key购买 nike

考虑以下片段 -

println String.class

输出是 -
class java.lang.String

我期待 String 的一些子类,因为它包含许多不属于 Java 类的成员。例如 -
println String.methods.size()
methods不是 Java 类的成员。

这个魔法是如何发生的?

最佳答案

Groovy 有一个元类注册表。当您在类上调用方法时,会检查注册表以查看该类实例是否存在元类扩展方法。

从标准文档 -

Each groovy object has a metaClass that is used to manage the dynamic nature of the language. This class intercepts calls to groovy objects to ensure that the appropriate grooviness can be added. Source

关于groovy - groovy 如何为 Java 类添加新方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17946855/

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