Change output for a particular occurence of a type with ReflectionToStringBuilder

4.1k views Asked by At

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  
1

There are 1 answers

0
Duncan Jones On

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();
}