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?

Michael
  • 3,411
  • 4
  • 25
  • 56
  • ```[1, 2, 3, 4, 5]``` is caused by ```ArrayList::toString```, it has nothing to do with ```ToStringStyle```. – zhh Aug 15 '18 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. – Michael Aug 15 '18 at 12:58
  • I'm not familiar with ```ToStringStyle```, Maybe you can override ```appendDetail(StringBuffer buffer, String fieldName, Collection> coll)```. – zhh Aug 15 '18 at 13:00
  • Hmm you might be on to something. I'll give it a try and get back to you. – Michael Aug 15 '18 at 13:02

2 Answers2

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,025
  • 5
  • 31
  • 88
zhh
  • 2,346
  • 1
  • 11
  • 22
  • Just tried this out. I've also overridden the `Map` one too. Works perfectly thank you! – Michael Aug 15 '18 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 – fakturk Jun 09 '20 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 
Joza100
  • 338
  • 4
  • 16
  • 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. – Michael Aug 15 '18 at 12:47
  • @Michael Does ReflectionToStringBuilder put strings inside of quotes when it makes the string? – Joza100 Aug 15 '18 at 12:50
  • I've updated my question. No it wouldn't be in quotes. – Michael Aug 15 '18 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. :/ – Joza100 Aug 15 '18 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. – Michael Aug 15 '18 at 12:59
  • @Michael Well, making your own ReflectionToStringBuilder might be the only option here. The class that you are using is just built to do it that way. Maybe you should just make one for your own purposes. It's easy to do tell me if you want me to update the answer and do that. – Joza100 Aug 15 '18 at 13:03