This week's book giveaway is in the Java in General forum.
We're giving away four copies of Think Java: How to Think Like a Computer Scientist and have Allen B. Downey & Chris Mayfield on-line!
See this thread for details.
Win a copy of Think Java: How to Think Like a Computer Scientist this week in the Java in General forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Auto toString of Variables

 
P Moran
Greenhorn
Posts: 3
  • Mark post as helpful
  • send pies
  • 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 ?
 
Rob Spoor
Sheriff
Pie
Posts: 20527
54
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • 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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic