Skip to content

Generator Custom Properties

Kostiantyn Shchepanovskyi edited this page Sep 26, 2015 · 3 revisions

In many cases we need to calculate something in a generator template, what in general should be avoided. Instead, custom object properties should be used. This way we are separating complex logic from templates - they should contain minimum logic.

// ...
Map<Class<?>, ObjectExtender<?>> extenderMap = new HashMap<>();
extenderMap.put(Proto.class, SimpleObjectExtender.<Proto>newBuilder()
        .property("javaPackage", JavaGenerator::javaPackage)
        .property("javaPackagePath", JavaGenerator::javaPackagePath)
        .build());
delegate = compilerFactory.create("io/protostuff/generator/java/message.stg", rendererMap, extenderMap);

Methods that provide values for custom properties are normal java methods:

public static String javaPackage(Proto proto) {
    DynamicMessage.Value javaPackage = proto.getOptions().get("java_package");
    if (javaPackage != null) {
        return javaPackage.getString();
    }
    return proto.getPackage().getValue();
};

public static String javaPackagePath(Proto proto) {
    String javaPackage = javaPackage(proto);
    return javaPackage.replace('.', '/');
};
Clone this wiki locally