好的-尝试查看/阅读,但不确定我是否对此有答案。
我有一个实用程序类,它在内部包装了一个静态 ConcurrentLinkedQueue。
实用程序类本身添加了一些静态方法 - 我不希望调用 new 来创建实用程序的实例。
我想拦截 getProperty 调用实用程序类 - 并在类定义中内部实现这些
我可以通过在实用程序类元类中添加以下内容来实现这一点,然后再使用它
UnitOfMeasure.metaClass.static.propertyMissing = {name -> println "accessed prop called $name"}
println UnitOfMeasure.'Each'
但是我想做的是在类定义本身中声明拦截。我在类定义中尝试过这个 - 但它似乎从未被调用
static def propertyMissing (receiver, String propName) {
println "prop $propName, saught"
}
我也试过
static def getProperty (String prop) { println "accessed $prop"}
但这也不叫。
所以除了在我使用之前在我的代码/脚本中添加元类之外,如何在想要捕获属性访问的实用程序类中声明
我目前的实际课程看起来像这样
class UnitOfMeasure {
static ConcurrentLinkedQueue UoMList = new ConcurrentLinkedQueue(["Each", "Per Month", "Days", "Months", "Years", "Hours", "Minutes", "Seconds" ])
String uom
UnitOfMeasure () {
if (!UoMList.contains(this) )
UoMList << this
}
static list () {
UoMList.toArray()
}
static getAt (index) {
def value = null
if (index in 0..(UoMList.size() -1))
value = UoMList[index]
else if (index instanceof String) {
Closure matchClosure = {it.toUpperCase().contains(index.toUpperCase())}
def position = UoMList.findIndexOf (matchClosure)
if (position != -1)
value = UoMList[position]
}
value
}
static def propertyMissing (receiver, String propName) {
println "prop $propName, saught"
}
//expects either a String or your own closure, with String will do case insensitive find
static find (match) {
Closure matchClosure
if (match instanceof Closure)
matchClosure = match
if (match instanceof String) {
matchClosure = {it.toUpperCase().contains(match.toUpperCase())}
}
def inlist = UoMList.find (matchClosure)
}
static findWithIndex (match) {
Closure matchClosure
if (match instanceof Closure)
matchClosure = match
else if (match instanceof String) {
matchClosure = {it.toUpperCase().contains(match.toUpperCase())}
}
def position = UoMList.findIndexOf (matchClosure)
position != -1 ? [UoMList[position], position] : ["Not In List", -1]
}
}
我很欣赏为静态实用程序类而不是实例级属性拦截执行此操作的秘诀,并在类声明中执行此操作 - 而不是在我进行调用之前添加到 metaClass。
只是为了让您可以看到实际的类和调用的脚本 - 我在下面附上了这些
我调用类的脚本看起来像这样
println UnitOfMeasure.list()
def (uom, position) = UnitOfMeasure.findWithIndex ("Day")
println "$uom at postition $position"
// works UnitOfMeasure.metaClass.static.propertyMissing = {name -> println "accessed prop called $name"}
println UnitOfMeasure[4]
println UnitOfMeasure.'Per'
像这样的错误
[Each, Per Month, Days, Months, Years, Hours, Minutes, Seconds]
Days at postition 2
Years
Caught: groovy.lang.MissingPropertyException: No such property: Per for class: com.softwood.portfolio.UnitOfMeasure
Possible solutions: uom
groovy.lang.MissingPropertyException: No such property: Per for class: com.softwood.portfolio.UnitOfMeasure
Possible solutions: uom
at com.softwood.scripts.UoMTest.run(UoMTest.groovy:12)