tags:

views:

241

answers:

2

The ProxyMetaClass and Iterceptor classes for intercepting arbitrary Groovy method calls is well documented. Is there also a way to intercept property accesses? When I try to do this by intercepting "getProperty", I still get the error message:

groovy.lang.MissingPropertyException: No such property: foo

+1  A: 

I'm not completely sure about the use-case that you're trying to solve, but likely you want one of either propertyMissing or getProperty (or maybe invokeMethod).

The first will let you intercept property requests when they don't actually exist on the object:

class Person {
    def name = "Ted"
    def propertyMissing(String name) { "my $name" }
}

def p = new Person()
assert "my address" == p.address
assert "my email" == p.email
assert "Ted" == p.name // property isn't missing

The second will let you intercept all property requests, even for defined properties:

class Person {
    def name = "Ted"
    def getProperty(String name) { "my $name" }
}

def p = new Person()
assert "my address" == p.address
assert "my email" == p.email
assert "my name" == p.name

If you're working with an existing class, you can either subclass it with one of these methods, or else add these methods to the metaClass:

String.metaClass.getProperty = { String name ->
    return "String's property $name"
}

assert "String's property foo" == "".foo
Ted Naleid
A: 

Your approach seems to be correct. Try some of the recipes here.

Clutching at straws: is the object you're calling methods on really of the class you've metaprogrammed? Sometimes due to polymorphism, you're not using the class you think you are.

slim