如何在Groovy中实现java.util.Map的类上使用propertyMissing [英] How to use propertyMissing on a class that implements java.util.Map in groovy

查看:230
本文介绍了如何在Groovy中实现java.util.Map的类上使用propertyMissing的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我了解到我们无法以与访问地图属性相同的方式访问地图属性其他类,因为可以在groovy中获取带有点符号的地图键.

I understand that we cannot access Map properties the same way we access them in other classes, because of the ability to get map keys with dot notations in groovy.

现在,对于实现java.util.Map的类,是否有办法仍可以通过使用propertyMissing来受益于expando元类?

Now, Is there a way, for a class that implements java.util.Map, to still benefit from the expando metaclass for using propertyMissing ?

这就是我要尝试的:

LinkedHashMap.metaClass.methodMissing = { method, args ->
    println "Invoking ${method}"
    "Invoking ${method}"
}

LinkedHashMap.metaClass.propertyMissing = { method, args ->
    println "Accessing ${method}"
    "Accessing ${method}"
}

def foo = [:]

assert "Invoking bar" == foo.bar() // this works fine
assert "Accessing bar" == foo.bar  // this doesn't work, for obvious reasons, but I'd like to be able to do that...

我一直在尝试通过自定义DelegatingMetaClasses,但没有成功...

I've been trying through custom DelegatingMetaClasses but didn't succeed...

推荐答案

不确定它是否适合您的用例,但是您可以在地图上使用Guava和withDefault方法...

Not sure it fits your use-case, but you could use Guava and the withDefault method on Maps...

@Grab( 'com.google.guava:guava:16.0.1' )
import static com.google.common.base.CaseFormat.*

def map
map = [:].withDefault { key -> 
    LOWER_UNDERSCORE.to(LOWER_CAMEL, key).with { alternate ->
        map.containsKey(alternate) ? map[alternate] : null
    }
}

map.possibleSolution = 'maybe'

assert map.possible_solution == 'maybe'

这样做的一个副作用是,在断言之后,映射包含两个键:值对:

One side-effect of this is that after the assert, the map contains two key:value pairs:

assert map == [possibleSolution:'maybe', possible_solution:'maybe']

这篇关于如何在Groovy中实现java.util.Map的类上使用propertyMissing的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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