Search code examples
javaannotationsxtend

How to do I add a parameter of type String to a generated java setter using Xtend active annotations?


I have the following snippet in my AbstractFieldProcessor.doTransformation override:

field.declaringType.addMethod('set'+ field.simpleName.toFirstUpper +'Input' )
    [


        addParameter("values", ########)
        addParameter("keys",field.type)
        body=
        '''
            this.click«field.simpleName.toFirstUpper»();
            «field.simpleName»Input.sendKeys("ABCDEFG");
        '''
    ]

How can I generate the parameter of type Strings for the "value" parameter. The field.type is not a String. How can I create a TypeReference for a String?


Solution

  • A TypeReference referencing type String can be obtained using the TypeReferenceProvider.getString() method.

    In practice you can use the TransformationContext interface (because it extends TypeReferenceProvider):

    override doTransform(MutableClassDeclaration annotatedClass, extension TransformationContext context)
    {
        // Add field of type String
        annotatedClass.addField("stringField") [
            type = string // Get TypeReference to type String
        ]
    }
    

    There are other useful methods in TypeReferenceProvider to get a TypeReference to other often used types, like getObject(), getPrimitiveX(), etc.


    To obtain a TypeReference to any type in general, first you should find the type then create a TypeReference to it. You can use the TransformationContext for this as well:

    1. Find the type using the TransformationContext.findTypeGlobally() or TransformationContext.findX() methods.
    2. Obtain TypeReference by calling TransformationContext.newTypeReference()

    For example to create a TypeReference to LinkedHashMap<String, Object> in the doTransform() method, you can use

    LinkedHashMap.findTypeGlobally.newTypeReference(string, object)