1

I would like to output all of the values for variables in an object.

Currently I am using ReflectionToStringBuilder but the problem is that it includes the [,] characters when outputting collections.

Here is an example.

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import org.apache.commons.lang.builder.ReflectionToStringBuilder;
import org.apache.commons.lang.builder.ToStringStyle;
public class Test 
{
 public int x = 10;
 public int y = 20;
 public String example = "This is some text, with a comma";
 public Collection<Integer> collection = new ArrayList<>(Arrays.asList(1, 2, 3, 4, 5));
 public static void main(String args[])
 {
 System.out.println(ReflectionToStringBuilder.toString(new Test(),
 ToStringStyle.NO_FIELD_NAMES_STYLE));
 }
}

Output

Test@efb78af[10,20,This is some text, with a comma,[1, 2, 3, 4, 5]]

I've tried defining my own ToStringStyle but it seems as though there aren't any options to remove the square brackets and commas.

import org.apache.commons.lang3.builder.ToStringStyle;
public class ValueOnlyToStringStyle extends ToStringStyle
{
 public static final ToStringStyle VALUE_ONLY = new ValueOnlyToStringStyle();
 private static final long serialVersionUID = 1L;
 private ValueOnlyToStringStyle() 
 {
 super();
 this.setContentStart("");
 this.setFieldSeparator(" ");
 this.setFieldSeparatorAtStart(true);
 this.setContentEnd("");
 this.setUseClassName(false);
 this.setUseFieldNames(false);
 this.setArrayContentDetail(true);
 this.setArrayStart(" ");
 this.setArrayEnd(" ");
 this.setArraySeparator(" ");
 this.setDefaultFullDetail(true);
 this.setNullText("");
 this.setSizeStartText("");
 this.setSizeStartText("");
 this.setFieldNameValueSeparator(" ");
 this.setUseShortClassName(false);
 this.setUseIdentityHashCode(false);
 this.setSummaryObjectStartText(" ");
 this.setSummaryObjectEndText(" ");
 }
}

Output

10 20 This is some text, with a comma [1, 2, 3, 4, 5]

What I need is to only get the values with no added characters.

10 20 This is some text, with a comma 1 2 3 4 5

How could this be achieved?

asked Aug 15, 2018 at 12:37
4
  • [1, 2, 3, 4, 5] is caused by ArrayList::toString, it has nothing to do with ToStringStyle. Commented Aug 15, 2018 at 12:55
  • This could be a problem. Is there any way I can achieve what I want with ToStringStyle? It needs to output the way I've displayed for collections. Commented Aug 15, 2018 at 12:58
  • I'm not familiar with ToStringStyle, Maybe you can override appendDetail(StringBuffer buffer, String fieldName, Collection<?> coll). Commented Aug 15, 2018 at 13:00
  • Hmm you might be on to something. I'll give it a try and get back to you. Commented Aug 15, 2018 at 13:02

2 Answers 2

3

I have tried the code on my machine, it should work on your example.

class MyToStringStyle extends ToStringStyle {
 public MyToStringStyle() {
 setFieldSeparator(" ");
 setUseFieldNames(false);
 setUseIdentityHashCode(false);
 setUseClassName(false);
 setContentStart("");
 setContentEnd("");
 }
 @Override
 protected void appendDetail(StringBuffer buffer, String fieldName, Collection<?> coll) {
 if (coll.isEmpty()) return;
 Iterator iter = coll.iterator();
 buffer.append(iter.next());
 while (iter.hasNext()) {
 buffer.append(" ").append(iter.next());
 }
 }
}
Faraz
6,3056 gold badges44 silver badges99 bronze badges
answered Aug 15, 2018 at 13:19
2
  • Just tried this out. I've also overridden the Map one too. Works perfectly thank you! Commented Aug 15, 2018 at 13:24
  • this solution solved my problem on picking the necessary part of the object problem and I liked it, it is so simple and well writen Commented Jun 9, 2020 at 15:43
1

I decided to edit the code because I have built a custom ReflectionToStringBuilder method. Here is the method:

public static String toString(Object object) {
 Class<?> clazz = object.getClass();
 Field[] fields = clazz.getDeclaredFields();
 StringBuilder stringBuilder = new StringBuilder();
 for (Field field : fields) {
 try {
 field.setAccessible(true);
 Object value = field.get(object);
 // check if the value is actually a list
 if (List.class.isAssignableFrom(value.getClass())) {
 // this for some reason gives the unchecked cast warning, but we actually are
 // checking it so don't worry!
 @SuppressWarnings("unchecked")
 List<Object> list = (List<Object>) value;
 for (Object element : list) {
 stringBuilder.append(element.toString()).append(" ");
 }
 } else if (value.getClass().isArray()) {
 Object[] array = (Object[]) value;
 for (Object element : array) {
 stringBuilder.append(element.toString()).append(" ");
 }
 } else {
 stringBuilder.append(value.toString()).append(" ");
 }
 } catch (IllegalArgumentException | IllegalAccessException e) {
 e.printStackTrace();
 }
 }
 return stringBuilder.toString();
}

I have tested it and it works perfectly.

My class:

int x = 0;
String string = "string0";
List<String> stringList = Arrays.asList("string1");
String[] stringArray = {"string3", "string4"};
public static void main(String[] args) {
 Test test = new Test();
 System.out.println(toString(test));
}

Output:

0 string0 string1 string3 string4 
answered Aug 15, 2018 at 12:44
6
  • What if one of my objects has a string with a "," contained in it? E.g. String sentence = "This is some text, with a comma". I wouldn't want it removed in this case. Commented Aug 15, 2018 at 12:47
  • @Michael Does ReflectionToStringBuilder put strings inside of quotes when it makes the string? Commented Aug 15, 2018 at 12:50
  • I've updated my question. No it wouldn't be in quotes. Commented Aug 15, 2018 at 12:54
  • @Michael Did you test that it wouldn't be in quotes or just assume? It doesn't really make sense that they didn't put it in quotes because then it looks like that comma is separating something too which it isn't. :/ Commented Aug 15, 2018 at 12:57
  • I've added the output after running it. It isn't in quotes. The code for the Test class is exactly what I ran. Commented Aug 15, 2018 at 12:59

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.