aspose file tools*
The moose likes Beginning Java and the fly likes Auto  toString of Variables Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Auto  toString of Variables" Watch "Auto  toString of Variables" New topic
Author

Auto toString of Variables

P Moran
Greenhorn

Joined: Sep 23, 2008
Posts: 3
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

Joined: Oct 27, 2005
Posts: 19760
    
  20

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.


SCJP 1.4 - SCJP 6 - SCWCD 5 - OCEEJBD 6
How To Ask Questions How To Answer Questions
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Auto toString of Variables