Tuesday, July 3, 2012

A quick way to output the fields of an object

The Apache Jakarta Commons Lang project has many useful classes, including the ToStringBuilder class. This class has a very handy set of static reflectionToString methods that use reflection to read the values of an object's fields and then display their values.


/** * Code snippet to work with ToStringBuilder from commons-lang jar with log4j */ 
package com; 
import org.apache.commons.lang.builder.ToStringBuilder; 
import org.apache.commons.lang.builder.ToStringStyle; 
import org.apache.log4j.Logger; 
/** * @author thanooj * */ 
class Test {
 private int eno; 
 private String ename; 
 private float sal; 
 public Test(int eno, String ename, float sal) {
  super(); 
  this.eno = eno; 
  this.ename = ename; 
  this.sal = sal; 
  } 
  // setters and getters 
  } 
public class ToStringBuilderTest {
/** * @param args */ 
public static void main(String[] args) {
 Logger logger = Logger.getLogger(ToStringBuilderTest.class); 
 Test test = new Test(1, "rama", 45000.0f); 
 logger.debug("Test object is created."); 
 String str1 = ToStringBuilder.reflectionToString(test, ToStringStyle.DEFAULT_STYLE); 
 logger.debug("Test object is displed in : " + str1); 
 String str2 = ToStringBuilder.reflectionToString(test, ToStringStyle.MULTI_LINE_STYLE); 
 logger.debug("Test object is displed in : " + str2); 
 String str3 = ToStringBuilder.reflectionToString(test, ToStringStyle.NO_FIELD_NAMES_STYLE); 
 logger.debug("Test object is displed in : " + str3); 
 String str4 = ToStringBuilder.reflectionToString(test, ToStringStyle.SHORT_PREFIX_STYLE); 
 logger.debug("Test object is displed in : " + str4); 
 String str5 = ToStringBuilder.reflectionToString(test, ToStringStyle.SIMPLE_STYLE); 
 logger.debug("Test object is displed in : " + str5); 
} 
}
 
 
log4j.properties :


 
# Root logger option
log4j.rootLogger=DEBUG, stdout
 
# Direct log messages to stdout
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target=System.out
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n 

package structure:


Output:


No comments: