【问题标题】:Groovy getProperty() on a static member静态成员上的 Groovy getProperty()
【发布时间】:2012-05-29 14:06:40
【问题描述】:

这个问题可能会说明我对 Groovy 类的工作原理缺乏了解,但我试图自己解决这个问题,但没有运气。我想在一个类上创建一个 getProperty() 方法,这样我就可以以 Groovyish 的方式引用成员变量。这与将它们公开不同,因为我确实希望在引用它们时完成一些逻辑。基本上,我正在尝试创建一个使用 ConfigSlurper 的配置 Groovy 类:

class Configuration implements GroovyObject {
  private static ConfigObject config  = new ConfigSlurper().parse(new File("testing.conf").toURI().toURL())

  //This method is illegal, but it illustrates what I want to do
  public static String getProperty(String prop){
    config.getProperty(prop)
  }
}

如果上面的类是合法的,我可以像这样引用配置项:

Configuration.dbUser

而不是这个,这需要使 ConfigObject 可用:

Configuration.config.dbUser

我知道,将配置对象公开会更容易,但知道如何做到这一点(或知道为什么不可能)将有助于我更好地理解 Groovy。

【问题讨论】:

    标签: class groovy static jvm static-members


    【解决方案1】:

    我可以让它工作的唯一方法是通过元类:

    class Configuration {
      private static ConfigObject config  = new ConfigSlurper().parse( "foo = 'bar'" )
    }
    
    Configuration.metaClass.static.propertyMissing = { name ->
      delegate.config[ name ]
    }
    
    println Configuration.foo
    

    不过可能有更好的方法...

    【讨论】:

    • 哦,你这个光荣的人。做到了,非常感谢!我曾尝试使用 metaClass 来定义 getProperty 静态方法,但这不起作用。我可以看到你做了什么,这很有意义。由于这只是用于不经常调用的配置内容,因此我可以使用这种方法,但它很昂贵并且可能不适合一般使用。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-08-23
    • 1970-01-01
    • 1970-01-01
    • 2012-10-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多