All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.cedarsoft.test.utils.ReflectionToString Maven / Gradle / Ivy

There is a newer version: 8.9.2
Show newest version
package com.cedarsoft.test.utils;

import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import java.lang.reflect.Field;

/**
 * @author Johannes Schneider ([email protected])
 */
public class ReflectionToString {
  private ReflectionToString() {
  }

  @Nonnull
  public static String toString( @Nullable Object object ) {
    if ( object == null ) {
      return "";
    }

    StringBuilder builder = new StringBuilder();
    builder.append( object.getClass().getName() ).append( " {\n" );

    Class daClass = object.getClass();
    while ( daClass != null ) {
      for ( Field field : daClass.getDeclaredFields() ) {
        field.setAccessible( true );

        builder.append( "\t" );
        builder.append( field.getName() ).append( ": " );
        try {
          builder.append( field.get( object ) );
        } catch ( IllegalAccessException e ) {
          builder.append( "" );
        }
        builder.append( "\n" );
      }
      daClass = daClass.getSuperclass();
    }

    builder.append( "}" );
    return builder.toString();
  }

}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy