CodeModel help needed to properly assign singleton.getinstance ()

I was able to generate 99% of what I need with the CodeModel API, but I'm at a dead end here ...

Using various "directXX" methods does not add import statements to the generated code, and I can work without methods like directXXX, except for one place in the generated class.

Suppose I need a generated method, for example:

/**
* Copies data from this Value-Obj instance, to the returned PERSON instance.
* 
* @return PERSON
* 
*/
public PERSON mapVOToPERSON() throws MappingException
{
   Mapper mapper = (com.blah.util.MapperSingleton.getMapperInstance());
   return mapper.map(this, PERSON.class);
}

You can see the right side of the Mapper destination in parens. Emitting the whole package + class was the only way I could find to simply declare β€œSomeSingleton.someMethod ()” on the right side and generate the generated code. Without adding MapperSingleton to the object model, there is no generated import ...

Questions:

1) ?

2) , Mapper ( MapperSingleton.

...

+1
2

, , ?

JCodeModel model = new JCodeModel();
JClass mapper = model.directClass("com.another.Mapper");
JClass factory = model.directClass("com.another.MapperSingleton");
JDefinedClass dc = model._class("com.example.Something");
JMethod method = dc.method(JMod.PUBLIC | JMod.STATIC, mapper, "testMethod");
method.body()._return(factory.staticInvoke("getMapperInstance"));
model.build(destinationDirectory);

package com.example;

import com.another.Mapper;
import com.another.MapperSingleton;

public class Something {


    public static Mapper testMethod() {
        return MapperSingleton.getMapperInstance();
    }

}

CodeModel 2.4

!

    JCodeModel model = new JCodeModel();
    JClass mapper = model.directClass("com.blah.util.Mapper");
    JClass factory = model.directClass("com.blah.util.MapperSingleton");
    JDefinedClass dc = model._class("com.example.Something");
    JDefinedClass person = model._class("com.example.PERSON");
    JMethod method = dc.method(JMod.PUBLIC, person, "mapVOToPERSON");
    JBlock block = method.body();
    JVar lhs = block.decl(mapper, "mapper", factory.staticInvoke("getMapperInstance"));
    JInvocation map = lhs.invoke("map");
    map.arg(JExpr._this()); 
    map.arg(person.dotclass());
    method.body()._return(map);
    model.build(destinationDirectory);

package com.example;

import com.blah.util.Mapper;
import com.blah.util.MapperSingleton;

public class Something {


    public PERSON mapVOToPERSON() {
        Mapper mapper = MapperSingleton.getMapperInstance();
        return mapper.map(this, PERSON.class);
    }

}
+4

, , JVar # init (JExpression). , RHS- .

, mapper JVar, init JVar JExpression, com.blah.util.MapperSingleton.getMapperInstance().

JExpression ( MapperSingleton), myclass.owner().ref(MapperSingleton.class).staticInvoke("getMapperInstance").

+1

Source: https://habr.com/ru/post/1796469/


All Articles