Groovy setter generation

Today, I have to generate setter to annote it at the compilation time.

I’ve previously generate getter as following :

classNode.addMethod(
      GroovyUtils.getsetName(GroovyUtils.GetSet.GET, fieldNode.getName())
      , Modifier.PUBLIC
      , fieldNode.getType()
      , new Parameter[]{}
      , new ClassNode[]{}
      , new ReturnStatement(new FieldExpression(fieldNode))
    );

But If I try to generate setter :

    classNode.addMethod(
      GroovyUtils.getsetName(GroovyUtils.GetSet.SET, fieldNode.getName())
      , Modifier.PUBLIC
      , new ClassNode (Void.TYPE)
      , new Parameter[]{ new Parameter(fieldNode.getType(), "value") }
      , new ClassNode[]{}
      , new ExpressionStatement(new BinaryExpression(new PropertyExpression(new VariableExpression("this"), fieldNode.getName()), Token.newSymbol(Types.EQUAL, 0, 0), new VariableExpression("value")))
    );

and … nothing, no setter generated …

It’s time to check groovy sources code and I had found :

    public MethodNode getSetterMethod(String setterName) {
        for (Object o : getDeclaredMethods(setterName)) {
            MethodNode method = (MethodNode) o;
            if (setterName.equals(method.getName())
                    && ClassHelper.VOID_TYPE==method.getReturnType()
                    && method.getParameters().length == 1) {
                return method;
            }
        }
        ClassNode parent = getSuperClass();
        if (parent!=null) return parent.getSetterMethod(setterName);
        return null;
    }
    VOID_TYPE = new ClassNode(Void.TYPE)

… Groovy developers use a new instance of ClassNode and use == operator. they compare memory address (the instance) but not the value.

Just changing “new ClassNode (Void.TYPE)” by “ClassHelper.VOID_TYPE” resolve my problem.

Advertisements

2 thoughts on “Groovy setter generation

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s