Reputation: 258
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.
Upvotes: 3
Views: 401
Reputation: 160301
If you don't want to build the string by hand, or manage changes manually, you might consider something like the Commons Lang ReflectionToStringBuilder.reflectionToString()
method, also available through the ToStringBuilder
class.
Upvotes: 5
Reputation: 2476
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
Upvotes: 5