user3659052 user3659052 - 6 months ago 10
Java Question

Shared multiple class for ToString implementation

I have multiple pojo classes using below code.

public class ToStringImpl {

public String toString(){
StringBuilder result = new StringBuilder();
String newLine = "\n";


result.append( this.getClass().getName() );
result.append( " Data {" );
result.append(newLine);

//determine fields declared in this class only (no fields of superclass)
Field[] fields = this.getClass().getDeclaredFields();

//print field names paired with their values
for ( Field field : fields ) {
result.append(" ");
try {
result.append( field.getName() );
result.append(": ");
//requires access to private field:
result.append( field.get(this) );
} catch ( IllegalAccessException ex ) {
System.out.println(ex);
}
result.append(newLine);
}
result.append("}");

return result.toString();
}

}


How do I call above class from different classes?
Suppose I have pojo classes called customer, store, inventory

public class Customer {

private String name;
private String address;

...getter...setter...

public String toString(){

ToStringImpl log = new ToStringImpl();
//how do I pass different classes here?
return log.toString();
}

}

public class Store {

private String logo;
private String type;

....getter...setter...
}

public class Inventory {

private boolean isAvailable;
private long index;

...getter...setter
}


for each class how do I pass different class? or if there are better way to do this? or would it be better to create toString as interface and implement it in each class and pass it as constructor?

Answer

What you can do is make the toString() method in the ToStringImpl class static. I wouldn't call it toString() though, change it to something like getClassString()

Example:

public static String getClassString(Object o)
{
    StringBuilder result = new StringBuilder();
    String newLine = "\n";

    result.append(o.getClass().getName());
    result.append(" Data {");
    result.append(newLine);

    // determine fields declared in this class only (no fields of
    // superclass)
    Field[] fields = o.getClass().getDeclaredFields();

    // print field names paired with their values
    for (Field field : fields)
    {
        result.append("  ");
        try
        {
            result.append(field.getName());
            result.append(": ");
            // requires access to private field:
            result.append(field.get(o));
        }
        catch (IllegalAccessException ex)
        {
            System.out.println(ex);
        }
        result.append(newLine);
    }
    result.append("}");

    return result.toString();
}

Then in your POJO classes, call it with:

public String toString()
{
    // how do I pass different classes here?
    // by passing the 'this' reference
    return ToStringImpl.getClassString(this);
}
Comments