[英]what is the best way to print all the values of the fields in a java class
I have a class called Product with some fields. 我有一个名为Product的类,其中包含一些字段。 I want to print all the values for a product object.
我想打印产品对象的所有值。
Class Product{
String code;
String description;
}
Product p = new product();
p.setCode("C");
p.setDescription("desc");
I want to print values of product instances ex 我想打印产品实例ex的值
Code:C Description:Desc.
I have around 100 classes with lot of fields in all the classes.What is the best way. 我有大约100个班级,所有班级都有很多领域。什么是最好的方法?
You'll want to override the toString() method in java.lang.Object. 您将要覆盖java.lang.Object中的toString()方法。
If you use Eclipse, you can autogenerate a toString method that does what you want. 如果使用Eclipse,则可以自动生成执行所需功能的toString方法。 Here's a good example of how to do that:
这是一个很好的例子:
http://idiot2genius.wordpress.com/2011/05/17/eclipse-generate-java-tostring-method-quickly/ http://idiot2genius.wordpress.com/2011/05/17/eclipse-generate-java-tostring-method-quickly/
There's a very useful class in the Apache Commons Lang project that you might find helpful as well: Apache Commons Lang项目中有一个非常有用的类,您可能会发现也很有用:
http://commons.apache.org/lang/api-2.4/org/apache/commons/lang/builder/ToStringBuilder.html http://commons.apache.org/lang/api-2.4/org/apache/commons/lang/builder/ToStringBuilder.html
如果您不想手工构建字符串或手动管理更改,则可以考虑使用类似于Commons Lang ReflectionToStringBuilder.reflectionToString()
方法的方法,该方法也可以通过ToStringBuilder
类获得。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.