Setters and getters - Pyknic/CodeGen GitHub Wiki

Very often when writing java programs, you find yourself writing set- and get-methods for every property in each class. This can be very tiresome, even if most IDE:s has built in support for generating them. When constructing a model in CodeGen, you can easily generate set:ers and get:ers in the following way:

final File f = File.of("org/example/codegen/Game.java")
    .add(Import.of(Type.of(ArrayList.class)))
    .add(Class.of("Game").public_()
        .add(Field.of("width", Default.INT_PRIMITIVE)
            .setValue(new NumberValue(640))
        )
        .add(Field.of("height", Default.INT_PRIMITIVE)
            .setValue(new NumberValue(480))
        )
        .add(Field.of("entities", Default.list(
            Type.of("org.example.codegen.Entity")
        )).setValue(new ReferenceValue("new ArrayList<>()")))
        .call(new SetGetAdd())
    ).call(new AutoImports(cg.getDependencyMgr()))
;

The code above will be generated into the following:

package org.example.codegen;

import java.util.ArrayList;
import java.util.List;

public class Game {
    private int width = 640;
    private int height = 480;
    private final List<Entity> entities = new ArrayList<>();
    
    /**
     * Sets the width of this Game.
     * @param width the new value.
     * @return a reference to this object.
     */
    public Game setWidth(int width) {
        this.width = width;
        return this;
    }
    
    /**
     * Gets the width of this Game.
     * @return the width.
     */
    public int getWidth() {
        return this.width;
    }
    
    /**
     * Sets the height of this Game.
     * @param height the new value.
     * @return a reference to this object.
     */
    public Game setHeight(int height) {
        this.height = height;
        return this;
    }
    
    /**
     * Gets the height of this Game.
     * @return the height.
     */
    public int getHeight() {
        return this.height;
    }
    
    /**
     * Adds the specified entity to this Game.
     * @param entity the new value.
     * @return a reference to this object.
     */
    public Game add(Entity entity) {
        this.entities.add(entity);
        return this;
    }
    
    /**
     * Gets the entities of this Game.
     * @return the entities.
     */
    public List<Entity> getEntities() {
        return this.entities;
    }
}

Note that the width and height properties are made private by default since to specified that you wanted to generate getters for them. CodeGen also recognize "entities" as a collection and creates a adder rather than a setter for it.

⚠️ **GitHub.com Fallback** ⚠️