Wednesday 17 May 2023

Utility class to generate getter and setter methods for a class property

Java bean is a class that is adhere to following conventions.

a.  Private fields with corresponding getter and setter methods.

b.   Class must have a public no-argument constructor.

 

For example, below snippet defines a Person java bean with two properties (name, age).

public class Person {
    private String name;
    private int age;

    public Person() {
        // Default constructor
    }

    // Getter for the 'name' property
    public String getName() {
        return name;
    }

    // Setter for the 'name' property
    public void setName(String name) {
        this.name = name;
    }

    // Getter for the 'age' property
    public int getAge() {
        return age;
    }

    // Setter for the 'age' property
    public void setAge(int age) {
        this.age = age;
    }
}

 

According to the Java bean conventions, Person class mantains

a.   A public no-arg constructor

b.   Each property (name, age) has a getter and setter methods.

 

Naming convention for getter and setter methods

According to the Java naming conventions, getter methods begins with the prefix "get" while setter methods begin with "set", followed by the name of the corresponding variable. It is customary to capitalize the first letter of the variable name in both cases.

 

Example

getName()
setName(String name)

Above methods are related the the property ‘name’.

 

Getter and setter conventions for a boolean property

For a boolean property, getter methods begins with the prefix "is" while setter methods begin with "set", followed by the name of the corresponding variable. It is customary to capitalize the first letter of the variable name in both cases.

 

Example

isActive()
setActive(boolean active)

Following utility class takes a Java POJO as input and generate getter and setter methods for it.

 


GetterAndSetterUtil.java

package com.sample.app.reflections.util;

import java.lang.reflect.Field;

public class GetterAndSetterUtil {
    private static final String THREE_SPACES = "   ";
    
    public static String setterName(String fieldName) {
        int len = fieldName.length();
        int setterNameSize = len + 3;
        char[] b = new char[setterNameSize];
        b[0] = 's';
        b[1] = 'e';
        b[2] = 't';
        char propertyFirstChar = fieldName.charAt(0);
        propertyFirstChar = Character.toUpperCase(propertyFirstChar);
        b[3] = propertyFirstChar;
        for (int i = 1; i < len; i++) {
            b[i + 3] = fieldName.charAt(i);
        }
        return new String(b);
    }

    public static String getterName(String fieldName) {
        int len = fieldName.length();
        int getterNameSize = len + 3;
        char[] b = new char[getterNameSize];
        b[0] = 'g';
        b[1] = 'e';
        b[2] = 't';
        char propertyFirstChar = fieldName.charAt(0);
        propertyFirstChar = Character.toUpperCase(propertyFirstChar);
        b[3] = propertyFirstChar;
        for (int i = 1; i < len; i++) {
            b[i + 3] = fieldName.charAt(i);
        }
        return new String(b);
    }

    public static String getterNameForBoolean(String fieldName) {
        int len = fieldName.length();
        int getterNameSize = len + 2;
        char[] b = new char[getterNameSize];
        b[0] = 'i';
        b[1] = 's';
        char propertyFirstChar = fieldName.charAt(0);
        propertyFirstChar = Character.toUpperCase(propertyFirstChar);
        b[2] = propertyFirstChar;
        for (int i = 1; i < len; i++) {
            b[i + 2] = fieldName.charAt(i);
        }
        return new String(b);
    }

    public static String getterCode(Field field) {
        boolean isBool = field.getType().equals(Boolean.TYPE);
        StringBuilder builder = new StringBuilder();
        builder.append("public").append(" ");
        if (isBool) {
            builder.append("Boolean").append(" ");
            builder.append(getterNameForBoolean(field.getName()));

        } else {
            builder.append(field.getType().getSimpleName()).append(" ");
            builder.append(getterName(field.getName()));
        }

        builder.append("()");
        builder.append("{\n").append(THREE_SPACES).append("return this.").append(field.getName()).append(";\n}");
        return builder.toString();
    }

    public static String setterCode(Field field) {
        StringBuilder builder = new StringBuilder();
        builder.append("public").append(" ").append("void").append(" ");
        builder.append(setterName(field.getName()));
        builder.append("(");
        builder.append(field.getType().getSimpleName());
        builder.append(" ");
        builder.append(field.getName());
        builder.append(")");

        builder.append("{\n").append(THREE_SPACES).append("this.").append(field.getName());
        builder.append("=").append(field.getName()).append(";\n}");
        return builder.toString();
    }

    public static void printGettersAndSetters(Class<?> clazz) {
        Field[] fields = clazz.getDeclaredFields();
        for (Field field : fields) {
            System.out.println();
            System.out.println(getterCode(field));
            System.out.println(setterCode(field));
        }
    }

}

GetterAndSetterUtilDemo.java

package com.sample.app.reflections.util;

public class GetterAndSetterUtilDemo {

    private static class Person {
        private String name;
        private int age;
        private boolean activeUser;

    }
    
    public static void main(String[] args) {
        GetterAndSetterUtil.printGettersAndSetters(Person.class);
    }
}

Output

public String getName(){
   return this.name;
}
public void setName(String name){
   this.name=name;
}

public int getAge(){
   return this.age;
}
public void setAge(int age){
   this.age=age;
}

public Boolean isActiveUser(){
   return this.activeUser;
}
public void setActiveUser(boolean activeUser){
   this.activeUser=activeUser;
}

 

Previous                                                 Next                                                 Home

No comments:

Post a Comment