groovy如何向Java类添加新方法? [英] How does groovy add new methods to Java classes?

查看:366
本文介绍了groovy如何向Java类添加新方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请考虑以下片段 -

  println String.class 

输出是 -

 类java.lang.String 

我期待String的一个子类,因为它包含许多不属于Java类的成员。例如 -

  println String.methods.size()

methods 不是Java类的成员。


解决方案

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



从标准文档 -


每个groovy对象都有一个metaClass,用于管理该语言的动态
性质。该类拦截对groovy对象
的调用,以确保可以添加适当的grooviness。 来源



Consider the following snippet -

println String.class

The output is -

class java.lang.String

I was expecting some subclass of String since it contains many members that are not a part of the Java class. For example -

println String.methods.size()

methods is not a member of the Java class.

How does this magic happen?

解决方案

Groovy has a metaclass registry. When you call a method on a class the registry is inspected to see if a metaClass extension method exists for that class instance.

From the standard documentation -

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如何向Java类添加新方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆