使用反射输出对象中变量的所有值

时间:2018-08-15 12:37:11

标签: java apache-commons apache-commons-lang apache-commons-lang3

我想输出对象中变量的所有值。

当前我正在使用ReflectionToStringBuilder,但问题是输出集合时它包含[,]字符。

这里是一个例子。

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

输出

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

我尝试定义自己的ToStringStyle,但似乎没有任何选择可以删除方括号和逗号。

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

    }
}

输出

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

我需要的是仅获取没有添加字符的值。

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

如何实现?

2 个答案:

答案 0 :(得分:1)

我决定编辑代码,因为我建立了一个自定义的ReflectionToStringBuilder方法。方法如下:

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

我已经对其进行了测试,并且效果很好。

我的课:

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

输出:

0 string0 string1 string3 string4 

答案 1 :(得分:1)

我已经在计算机上尝试过该代码,它可以在您的示例中正常工作。

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