自动初始化由 JCodeModel 创建的字段

auto-initialize Fields created by JCodeModel

我通过 Json 创建了一个新的 Java class,即:

{
    "package" : "crud.vaadin",
    "className" : "StudentForm",
    "extension" : "AbstractForm",
    "extensiongeneric" : "Person",
    "properties" : {
        "Name" : {
            "type" : "MTextField"
        },
        "Email" : {
            "type" : "MTextField"
        }
    },
    "model" : "Person"
}

将生成:

package crud.vaadin;

public class StudentForm extends AbstractForm<Person>
    {

        private MTextField Email;
        private MTextField Name;

    }

我使用 JCodeModel 生成 StudentForm,Field 生成方法如下所示:

    public void createFields(Map<String, Object> properties, JDefinedClass jc, JCodeModel model) {
            for(String key : properties.keySet()){
            //getType returns MTextField and key is either Email or Name
                String type = getType(prop.get(key));
                String name = key;
                try {
                    JType jt = model.parseType(type);
                    JFieldVar field = jc.field(JMod.PRIVATE, jt, name);
                } catch (ClassNotFoundException e) {
                    e.printStackTrace();
                }
            }
        }

但我想在创建源时初始化字段。

private MTextField email = new MTextField("Email");

有没有办法通过初始化来扩展 JFieldVar?

您只需使用 .field 调用指定初始化 JExpression,如下所示:

JFieldVar field = jc.field(JMod.PRIVATE, jt, name, JExpr._new(jt).arg(name));