• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Liutauras Vilda
  • Paul Clapham
Sheriffs:
  • paul wheaton
  • Tim Cooke
  • Henry Wong
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Piet Souris
Bartenders:
  • Mike London

Auto toString of Variables

 
Greenhorn
Posts: 3
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Howdie folks,

This is probably simple, I come from a Perl background so please bare with me if I speak out of turn.

Right now I want to simply create a generic toString override for my class, given I effectively want to just add a key value for every variable and print the variable e.g.



I think you can see what I have started, but is there a better way ? as right now got to add every single variable ?
 
Sheriff
Posts: 22716
129
Eclipse IDE Spring VI Editor Chrome Java Windows
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Originally posted by P Moran:
Right now I want to simply create a generic toString override for my class, given I effectively want to just add a key value for every variable and print the variable



Of course that's still tedious.

If you want you can use reflection:

1) Without this check, your toString will always start with VType@abcdef123 or something similar.

2) Class.getDeclaredFields only returns the fields that are declared in the class itself, not those already declared in the super class. That's what getFields() is for.

3) field.get(this) is used to get the value of the field for the current instance.


Now be aware that this will include ALL fields. Using field.getModifiers() and the static methods in java.lang.reflect.Modifier you could filter out some, like static fields.
 
reply
    Bookmark Topic Watch Topic
  • New Topic