What is Groovy's MetaClass used for?

前端 未结 2 1257
傲寒
傲寒 2020-12-10 01:50

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

2条回答
  •  北荒
    北荒 (楼主)
    2020-12-10 02:23

    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

提交回复
热议问题