Advertisement
Guest User

Untitled

a guest
May 22nd, 2017
47
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.84 KB | None | 0 0
  1. @Override
  2. public String toString() {
  3. StringBuilder result = new StringBuilder();
  4. String newLine = System.getProperty("line.separator");
  5.  
  6. result.append( this.getClass().getName() );
  7. result.append( " Object {" );
  8. result.append(newLine);
  9.  
  10. //determine fields declared in this class only (no fields of superclass)
  11. Field[] fields = this.getClass().getDeclaredFields();
  12.  
  13. //print field names paired with their values
  14. for ( Field field : fields ) {
  15. result.append(" ");
  16. try {
  17. result.append( field.getName() );
  18. result.append(": ");
  19. //requires access to private field:
  20. result.append( field.get(this) );
  21. } catch ( IllegalAccessException ex ) {
  22. System.out.println(ex);
  23. }
  24. result.append(newLine);
  25. }
  26. result.append("}");
  27.  
  28. return result.toString();
  29. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement