简体   繁体   中英

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. 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

Code:C Description:Desc.

I have around 100 classes with lot of fields in all the classes.What is the best way.

You'll want to override the toString() method in java.lang.Object.

If you use Eclipse, you can autogenerate a toString method that does what you want. Here's a good example of how to do that:

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:

http://commons.apache.org/lang/api-2.4/org/apache/commons/lang/builder/ToStringBuilder.html

如果您不想手工构建字符串或手动管理更改,则可以考虑使用类似于Commons Lang ReflectionToStringBuilder.reflectionToString()方法的方法,该方法也可以通过ToStringBuilder类获得。

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM