什么是Groovy的MetaClass用于? [英] What is Groovy's MetaClass used for?

查看:107
本文介绍了什么是Groovy的MetaClass用于?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

没有Meta-Class在Java中。您可能在考虑 Groovy的MetaClass


Groovy中的MetaClass定义了任何给定的Groovy或Java
类的
行为。 MetaClass接口定义了
两部分。客户端API是通过扩展
MetaObjectProtocol接口定义的
,以及与Groovy运行时
系统的
定义的合同。通常,编译器和
Groovy运行时引擎与此类的
方法进行交互,而MetaClass
客户端与由MetaObjectProtocol
接口定义的方法
交互







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



这是Groovy用于扩展Java JDK对象



示例:

  Object.class.metaClass.explode { - > printlnBoom!$ {delegate}爆炸!} 
SomeString.explode();
12345.explode();

输出:


繁荣! SomeString爆炸!

轰炸! 12345爆炸!

要获得更高级的用法,请阅读以下内容: MetaClass


What is the use of Meta-Class in Groovy and other OO programming languages?

解决方案

There is no Meta-Class in Java. You're probably thinking of 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


The Groovy MetaClass lets you assign behavior and state to Classes at runtime without editing the original source code, it's a layer above the original Class.

It's the mechanism used by Groovy to extend the Java JDK objects.

Example:

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

Output:

Boom! SomeString Exploded!
Boom! 12345 Exploded!

For more advanced usage, read this: MetaClasses

这篇关于什么是Groovy的MetaClass用于?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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