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
Stringify a JavaScript ObjectUse the JavaScript function JSON. stringify() to convert it into a string. const myJSON = JSON. stringify(obj);
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.
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]
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With