Object to String Helper2
Google Guava is a java library with lot of utilities and reusable components.
This requires the library guava-10.0.jar to be in classpath.
The following example shows using Objects.toStringHelper() API.
package com.bethecoder.tutorials.guava.base_tests;
import java.util.Date;
import com.bethecoder.tutorials.guava.common.Student;
import com.google.common.base.Objects;
public class Object2StringHelperTest2 {
/**
* @param args
*/
public static void main ( String [] args ) {
Student student = new Student ( "Sriram" , 2 , "Chess" ) ;
String str = Objects.toStringHelper ( Student. class ) .toString () ;
System.out.println ( str ) ;
str = Objects.toStringHelper ( Student. class )
.add ( "name" , student.getName ())
.toString () ;
System.out.println ( str ) ;
str = Objects.toStringHelper ( "MyStudent" )
.add ( "name" , student.getName ())
.add ( "age" , student.getAge ())
.toString () ;
System.out.println ( str ) ;
str = Objects.toStringHelper ( "MyStudent" )
.add ( "name" , student.getName ())
.add ( "age" , student.getAge ())
.addValue ( new Date ())
.toString () ;
System.out.println ( str ) ;
}
}
It gives the following output,
Student{}
Student{name=Sriram}
MyStudent{name=Sriram, age=2}
MyStudent{name=Sriram, age=2, Sat Nov 19 19:28:43 IST 2011}