Java J2EE Portal
Enterprise Java Station
J2EE curve
Java News / Articles
Java News / Articles
Kill The Java Language - A Message For Scripting Language Leads
J2EE vs JavaEE - Simplify programming
Integrating and Interoperating between J2EE and .NET Solutions
Processing...
Buy Java, Deals On Software Technology Store
Click here for great deals on computers, laptops, software and books
Simplifying Java with Jakarta Commons Lang PDF Print
Written by Harshad Oak   
May 17, 2006 at 11:52 PM
Generate the toString() Method

Methods like equals(), toString(), and hashCode() are used on a regular basis. However, when it comes to actually writing implementations for these methods, not only are most of us reluctant to do that but we are also not sure how exactly and easily to write them. The builder package provides utility classes that can help you easily create implementations for these methods. In most cases it just takes one line of code. We will look at the toString capabilities of Lang.

The toString() method

You might have noticed in Listing 4 that even if we just pass an object of java.util.Date to System.out.println(), the output we get is a proper display of the date and time. This is possible because when you just pass an object reference, the toString() method gets called automatically. So in our example we are essentially calling the toString() method of the java.util.Date class and the proper output we get is because someone has taken the trouble to override the toString() method from the java.lang.Object class in the java.util.Date class.

If the toString() method is not overridden, the output you get is just the name of the class and the hashcode. No data in the class will get displayed. So if you have written a new class and wish to get a proper output on print, you need to override the toString() method in your class.

Listing 6. The toString() method

public class Computer {

    String processor;
    String color;
    int cost;

    /** Creates a new instance of Computer */
    public Computer(String processor, String color, int cost) {
        this.processor=processor;
        this.color=color;
        this.cost=cost;
    }

    public static void main(String[] args) {
        Computer myComp=new Computer("Pentium","black",1000);
        System.out.println(myComp);
    }
    
    public String toString(){
        return ToStringBuilder.reflectionToString(this);
        /*
        return ToStringBuilder.reflectionToString(this
            , ToStringStyle.SHORT_PREFIX_STYLE);
        return ToStringBuilder.reflectionToString(this
            , ToStringStyle.MULTI_LINE_STYLE);
        return new ToStringBuilder(this)
            .append("processor", processor).toString();
         */
    }
}

Listing 6 shows a Computer class that has three fields in it. The toString() method is what is special. The call to the reflectionToString() method is able to figure out which are the fields in the class, and then prints their name and value. In the main() method, we simply create an instance of the class and then print it. The output in this case is dev2dev.Computer@f6a746[processor=Pentium,color=black,cost=1000].

So if you don't wish to put too much effort into it and yet require toString() implementations for your classes, there is no easier way than to copy and paste these two lines of code into all your classes. If you wish to have more control over what is generated, look at the commented options. You can apply various styles to the output or even build the entire output by creating a new instance of ToStringBuilder. The output, if you were to execute each of the four return statements in the listed order, is shown in Listing 7.

Listing 7. The four possible outputs based on the ToStringBuilder method used

1) dev2dev.Computer@f6a746[processor=Pentium,color=black,cost=1000]
2) Computer[processor=Pentium,color=black,cost=1000]
3) dev2dev.Computer@f6a746[
   processor=Pentium
   color=black
   cost=1000
   ]
4) dev2dev.Computer@192d342[processor=Pentium]




Add This Feed Button

Enter your Email


Java Expert Interviews
Sameer Tyagi Sun
Understanding Web Services and SOA
GuillaumeLaforgeGroovy
Groovy bridges the scripting and the enterprise Java worlds
EclipseExecutiveDirectorMikeMilinkovich
Eclipse is focused on closing in on Visual Studio - Switching campaigns are for marke
Processing...
Go to top of page  Home |
SiteMap

Copyright 2004 to 2008 Rightrix Solutions. All rights reserved. All product names are trademarks of their respective companies. Java and all Java-based marks are trademarks or registered trademarks of Sun Microsystems, Inc. in the United States and other countries. Rightrix Solutions and IndicThreads.com are independent of Sun Microsystems, Inc.

Views expressed at IndicThreads.com reflect the views of the authors alone, and do not necessarily reflect those of IndicThreads.com. IndicThreads.com and it's authors are not responsible for reader comments and opinions.

Enterprise Java J2EE JEE Portal >> IndicThreads.com