1

I'm using the Apache Common Lang ReflectionToStringBuilder to recursively give me a toString for my entities.

I have a custom ToStringStyle that I'm using to give me a slightly modified output, and I'm omitting some variables that I don't want to appear.

My question is for a particular object type, can you specify a particular attribute to print.

For example: I have two Person Objects each has an ID value, and a Relationship Object called BestFriend.

public class Person {

int id;
String name;
int age;
Person bestfiend;


public void setBestFriend(Person bestFriend){
    this.bestfiend = bestFriend;
  }
}

Currently what is happening, is when I link the two Person Objects to be Bestfriends, ReflectionToStringBuilder is writing the entire Person Object for the value of the Bestfriend.

Person[  
id = 0001  
name = John  
age = 25  
bestFriend=Person@25eb3d2[  
                id = 0002  
                name = Mary  
                age = 29  
                ]  
]  

Can you specify that for all Relationship Objects give me the value of the ID rather then the whole Person Object?

Person[  
id = 0001  
name = John  
age = 25  
bestFriend= 0002  
zb226
  • 9,586
  • 6
  • 49
  • 79
Newmanater
  • 153
  • 1
  • 12
  • The `ReflectionToStringBuilder` class only allows you to exclude fields, not change the way they are printed. You could instead use the `ToStringBuilder` class to define how to print a `Person` from within the `toString()` method. – Duncan Jones Nov 12 '14 at 07:56
  • Hi, I'm already implementing a class that extends ToStringStyle to give me a custom output (mainly formatting) can I specify in that class to do the required behavior? – Newmanater Nov 12 '14 at 08:00
  • You probably could, although that might get a bit hairy. Is there any reason you must use `ReflectionToStringBuilder` instead of `ToStringBuilder`? It would be much easier with the latter to just add the ID field of the best friend. – Duncan Jones Nov 12 '14 at 08:09
  • The only reason is that you can add and remove fields without have to worry about adding/removing to/from the toString method. – Newmanater Nov 12 '14 at 08:14

1 Answers1

6

The following code snippet shows how to selectively exclude the best friend field, then only add the ID value. You have to check for null to avoid a NPE.

@Override
public String toString() {
  ReflectionToStringBuilder builder = new ReflectionToStringBuilder(this);
  builder.setExcludeFieldNames("bestfriend");
  builder.append("bestfriend", (bestfriend == null) ? "None" : bestfriend.id);
  return builder.build();
}
Duncan Jones
  • 67,400
  • 29
  • 193
  • 254