Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert Class Object to Human Readable String

Tags:

java

string

Is there any way in which I can automatically convert a Custom Class Object into a human readable string?

e.g. consider the following class:

class Person {
    String Name;
    int Salary;
    ...
}

Person p = new Person();
p.setName("Tony");
p.setSalary(1000);

I need to get something like:

Person: Name="Tony", Salary=1000
like image 844
MBZ Avatar asked Jul 02 '12 10:07

MBZ


People also ask

How do you turn an object into a string in JavaScript?

Stringify a JavaScript ObjectUse the JavaScript function JSON. stringify() to convert it into a string. const myJSON = JSON. stringify(obj);

How do you convert a class object to a string in Python?

Python is all about objects thus the objects can be directly converted into strings using methods like str() and repr(). Str() method is used for the conversion of all built-in objects into strings. Similarly, repr() method as part of object conversion method is also used to convert an object back to a string.


2 Answers

Importing Commons Lang you could use ToStringBuilder

Check method reflectionToString(java.lang.Object), this will create automatically the representation you are expecting.

This code:

Person p = new Person();
p.setName("Tony");
p.setSalary(1000);

System.out.println(ToStringBuilder.reflectionToString(p));

results this string:

Person@64578ceb[Name=Tony,Salary=1000]
like image 178
Francisco Spaeth Avatar answered Sep 18 '22 04:09

Francisco Spaeth


This is basically what toString is for. But given you want this done automatically, you can create some general service that can do it. Use reflection to iterate all fields, and then print each one's name and value. Simplest way to print their values would be by using their toString, but you can also pass them into that printing service recursively on some cases (you'll have to find the halt condition, of course).

For example, on some class PrintUtils have:

public static void printFields(Object o) {
    System.out.print(o.getClass.getSimpleName() + ": ");
    for (Field field : o.getClass().getDeclaredFields()) {
        field.setAccessible(true);     // you also get non-public fields
        System.out.print(field.getName() + " = " + field.get(o) + ", ");
    }
}

You'll have to handle exceptions etc. and possibly better format the output, of course. Also, this only print fields declared in the current class. If you want fields declared higher in the inheritance hierarchy, you'll have to work a bit more. Lastly, using reflection is much slower than just having a regular toString. If using toString is possible, it is preferable.

like image 26
eran Avatar answered Sep 19 '22 04:09

eran