Search code examples
javaoutputtostringjooqpojo

How to remove POJO class name from the output string?


I have below POJO

package com.beans.test;

import lombok.Data;

@Data
public class Person {

    private int id;

    private String name;

    private Integer age;

    private Boolean isEmployed;

    private String address;

}

Query to fetch Person info

public class testTable {

public Person getPersonInfo(final int id) {

return dsl.select(PERSON_INFO.NAME,
                  PERSON_INFO.AGE,
                  PERSON_INFO.IS_EMPLOYED,
                  PERSON_INFO.ADDRESS)
          .from(PERSON_INFO)
          .where(PERSON_INFO.ID.equals(id))
          .fetchOneInto(Person.class)
}
}

I need to print the output of the query as string.

Person person = testTable.getPersonInfo(id);
String personInfo = person.toString();
System.out.println("personInfo = ", personInfo);

Output :- personInfo = Person(name=TestName,age=TestAge,isEmployed=true,address=TestAddress)

Desired Ouput :- personInfo = name=TestName,age=TestAge,isEmployed=true,address=TestAddress

How can I remove the POJO class name from the desired output string ?(As shown in the Desired Output)


Solution

  • My solution

    package com.company;
    
    import lombok.Data;
    
    public class Main {
    
        @Data
        public static class Person {
    
            private int id;
    
            private String name;
    
            private Integer age;
    
            private Boolean isEmployed;
    
            private String address;
    
        }
    
        public static String getClassName(Class clazz){
            if(clazz.getDeclaringClass() == null)
            {
                return clazz.getSimpleName();
            }
            return getClassName(clazz.getDeclaringClass()) + "." + clazz.getSimpleName(); //Recursive - complete class name.
        }
    
        public static String toStringRemovingClassName(Object obj)
        {
            String pattern = String.format("^%s\\(|\\)$", getClassName(obj.getClass())); //Matches "<ClassName>(" at begin or ")" at end.
            return obj.toString().replaceAll(pattern, "");
        }
    
        public static void main(String[] args) {
            var person = new Person();
            System.out.println("personInfo = " + toStringRemovingClassName(person));
            person.id = 1;
            person.address = "\"952 NW 80th St, Miami, FL 33150\"";
            person.name = "Jeff";
            person.age = 30;
            person.isEmployed = true;
    
            System.out.println("personInfo = " + toStringRemovingClassName(person));
        }
    }
    
    

    Output

    personInfo = id=0, name=null, age=null, isEmployed=null, address=null
    personInfo = id=1, name=Jeff, age=30, isEmployed=true, address="952 NW 80th St, Miami, FL 33150"
    

    output