Search code examples
groovycoercion

Does Groovy "as" operator create a subclass at run time for User defined classes?


In Groovy When I write the below code in a groovy script.

class Emp {
    public String getId() {
         return "12345";
    }
}

def coercedInstance = [ 
   getId: {
     "99999"
    }
] as Emp

println new Emp().getId()
println coercedInstance .getId()

Using the as Operator here, am I creating a sub class of the actual Emp class at runtime and providing the method body at run time?

I have seen other stack overflow articles and i have learnt that Groovy uses DefaultGroovyMethods.java & DefaultTypeTransformation.java to do the coercion. But could not figure out if it was subclassing or not.


Solution

  • Yes, an as operator creates an object which type is a subclass of the target class. Using DefaultGroovyMethods.asType(Map map, Class clazz) generates (in a memory) a proxy class that extends given base class.

    class Emp {
    
        public String getId() {
            return "12345";
        }
    }
    
    def coercedInstance = [
        getId: {
            "99999"
        }
    ] as Emp
    
    assert (coercedInstance instanceof Emp)
    assert (coercedInstance.class != Emp)
    assert (Emp.isAssignableFrom(coercedInstance.class))
    
    println coercedInstance.dump() // <Emp1_groovyProxy@229c6181 $closures$delegate$map=[getId:coercion$_run_closure1@7bd4937b]>
    

    What happens in your case specifically is the following: