【问题标题】:groovy define metaclass with its own custom methods and set it for the objectgroovy 用自己的自定义方法定义元类并为对象设置它
【发布时间】:2016-05-04 04:10:49
【问题描述】:

是否可以使用其自定义方法为groovy 中的对象设置metaclass?我的意思是某种动态继承...

比如这样的

class Original {
    def my_method() { }
}

class Meta {
    def meta_method() { }
}

def obj = new Original()
obj.metaClass = new Meta()

obj.meta_method()

【问题讨论】:

    标签: groovy metaclass


    【解决方案1】:

    您可以使用特征来实现这种事情。这比直接操作元类要“高级一点”

    ​class Original {
      def my_method() { } 
    }  
    
    trait Meta {
      def meta_method() { } 
    }  
    
    def obj = new Original()​.withTraits Meta
    ​obj.meta_method()​
    

    见:http://docs.groovy-lang.org/next/html/documentation/core-traits.html#_implementing_a_trait_at_runtime

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-02-14
      • 1970-01-01
      • 2015-06-17
      • 1970-01-01
      • 1970-01-01
      • 2022-12-28
      • 1970-01-01
      相关资源
      最近更新 更多