CodeModel help needed for right-hand singleton.getinstance() assignment

久未见 提交于 2019-12-01 13:17:41

Maybe I don't understand the question fully but, is code like this OK?

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);

It will generate

package com.example;

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

public class Something {


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

}

This is with CodeModel 2.4

EDIT! Second try

    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);

Generates

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);
    }

}

Peter, I think what you're looking for is JVar#init(JExpression). This is the method you should use to create the RHS initialisation of a variable or field declaration.

So, when you declare mapper and get a JVar, call init on this JVar and pass in the JExpression that represents your call to com.blah.util.MapperSingleton.getMapperInstance().

In order to create the JExpression you need (one that represents a call to MapperSingleton), use myclass.owner().ref(MapperSingleton.class).staticInvoke("getMapperInstance").

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!