Is there any way in which I can automatically convert a Custom Class Object into a human readable string?
eg 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
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.
sure you can override the toString
method of class.
as follow:
class Person {
String name;
int salary;
...
@Override public String toString() {
return "Person: Name='" + name + "', Salary=" + salary;
}
}
refer for more details https://blogs.oracle.com/CoreJavaTechTips/entry/writing_tostring_methods_tech_days
我认为你可以使用ToStringBuilder ,它是commons-lang
一部分。
class Person {
String Name;
int Salary;
...
@Override
public String toString() {
return "Person: Name = " + Name + "," +
"Salary="+Salary;
}
}
Person p = new Person();
p.setName("Tony");
p.setSalary(1000);
System.out.println(p.toString());
One way to do it is to rely on Apache Commons BeanUtils.describe . This will produce a Map
of bean's properties, which converts to a string nicely via Map.toString
. If you want something more custom, you'll need to dig into the reflection API.
你可以使用java中的消息格式: https ://docs.oracle.com/javase/tutorial/i18n//message.html seperate variable by - 你的类中有一个可读的字符串!
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.