【问题标题】:Groovy newInstance() method missing after set metaClass设置元类后缺少 Groovy newInstance() 方法
【发布时间】:2011-11-25 02:23:44
【问题描述】:

我定义了一个元类

class MyMetaClass extends DelegatingMetaClass {
  MyMetaClass(Class theClass){
    super(theClass)
    println theClass
  }
  Object invokeStaticMethod(Object object, String methodName, Object[] arguments) {
    if(methodName == 'save') {
      println 'save method'
      return 
    } else {
      return super.invokeMethod(object, methodName, arguments)
    }
  }
}

和A类:

class A {
  private String a
  String getA(){
    return a
  }
}

并注册元类:

def amc = new MyMetaClass(A)
amc.initialize()
InvokerHelper.metaRegistry.setMetaClass(A, amc)

现在,我尝试使用以下方法创建实例:

A a2 = A.class.newInstance()

我得到错误:

Caught: groovy.lang.MissingMethodException: No signature of method: A.newInstance() is applicable for argument types: () values: []
at MyMetaClass.invokeStaticMethod(MyMetaClass.groovy:37)
at test.run(test.groovy:139)

这是什么原因?我的理解是我已经将其他方法委托给超类,newInstance() 方法应该仍然可以调用。

【问题讨论】:

    标签: groovy metaclass


    【解决方案1】:

    我认为:

      return super.invokeMethod(object, methodName, arguments)
    

    应该是:

      return super.invokeStaticMethod(object, methodName, arguments)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-01-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-11-29
      • 2016-05-22
      • 1970-01-01
      相关资源
      最近更新 更多