How to make a Groovy class look like Map to Java code without using the Map interface explicitly

I want to implement a custom class like Map, where most of the functions are delegated to a nested instance of a map delegate. And I want this class to look like a map for the "true" Java classes. So I tried to do the following:

class ConfigurationMap implements Map {
    def inner = [:]

    def methodMissing(String methodName,methodArgs) {
        return inner.invokeMethod(methodName,methodArgs)
    }

    // my methods here
    ...

And, of course, this will not work :-( Groovy requires the class to implement the methods of the Map interface, even though they were processed by missedMissing () at run time. If I delete the sentence implements:

class ConfigurationMap {
    def inner = [:]

    def methodMissing(String methodName,methodArgs) {
        return inner.invokeMethod(methodName,methodArgs)
    }

it works for Groovy (i.e. the instance really behaves like a Map), but I cannot use it as a map from Java code:

ConfigurationMap cm = ConfigParser.parseConfig("foo.cfg");
assertEquals(0,cm.size()); // size() method is not defined :-(

, (.. Map ) - Map Java?

+3
1

, @Delegate, - Java.

class ConfigurationMap implements Map {
    @Delegate Map inner = [:]

    def myMethod() {
        return true
    }
}

ConfigurationMap cm = new ConfigurationMap()
cm.foo = "bar"
assert "bar" == cm.foo
assert true == cm.myMethod()
+6

All Articles