Michael
Michael

Reputation: 4351

Output all of the values for variables in an object using reflection

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?

Upvotes: 1

Views: 1784

Answers (2)

zhh
zhh

Reputation: 2406

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

Upvotes: 3

Joza100
Joza100

Reputation: 356

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 

Upvotes: 1

Related Questions