java实现控制台输出任何数据类型内容、对象转字符串操作

java实现任何数据类型内容转换成字符串并格式化 支持嵌套各种套娃

    • 1. 添加依赖:
    • 2. 代码:
    • 3. 测试:
    • 4. 测试结果:

之前经常做数据加工,加工的对象也是各种类型,数组、集合、XML、JSON等等,想要写日志可是个麻烦事,各种转换,然后花了点时间写了个通用方法,可能不是最优,但是在项目中使用已经足够了,已经用了三年了,今天决定和大家分享一下,如果有更好的方法欢迎评论指点。

1. 添加依赖:

首先,你需要在项目的pom.xml文件中添加Dom4j的依赖(没有xml对象不用添加)。具体如下:

   <dependency>
     <groupId>dom4jgroupId>
        <artifactId>dom4jartifactId>
        <version>1.6.1version>
    dependency>

2. 代码:

	/**
	* @version 创建时间 2020年10月28日 下午4:12:56
	* @author 作者 猴子请来的坑逼
	* @Modifier 修改人 
	* @description 对象转字符串
	* @param object
	*/
	public static Object converter(Object object) {
        if (object == null) {
            return object;
        } else if (object instanceof Element) {
            return convertElementToString((Element) object);
        } else if (object.getClass().isArray()) {
            return convertArrayToString(object);
        } else if (object instanceof Collection) {
            return convertCollectionToString(object);
        } else if (object instanceof Map) {
            return convertMapToString(object);
        } else if (object instanceof Document) {
            return convertDocumentToString(object);
        } else {
            return object;
        }
    }

    private static String convertElementToString(Element ele) {
        String string = ele == null ? "" : ele.asXML();
        try {
            ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
            OutputFormat format = OutputFormat.createPrettyPrint();
            format.setEncoding("utf-8");
            XMLWriter writer = new XMLWriter(byteArrayOutputStream, format);
            writer.write(putToDocument(ele.createCopy()));
            string = new String(byteArrayOutputStream.toByteArray(), "utf-8");
        } catch (Exception e) {

        }
        return string;
    }

    public static Document putToDocument(Element element) {
        Document doc = element.getDocument();
        if (doc == null) {
            Element parent = element;
            while (parent.getParent() != null) {
                parent = parent.getParent();
            }
            doc = DocumentHelper.createDocument();
            doc.add(parent);
        }
        return doc;
    }

    private static String convertArrayToString(Object object) {
        StringBuilder sb = new StringBuilder();
        Object[] array = (Object[])object;
        sb.append("[");
        for (int i = 0; i < array.length; i++) {
            if (i != 0) {
                sb.append(", ");
            }
            Object value = array[i];
            sb.append(converter(value));
        }
        sb.append("]");
        return sb.toString();
    }

    private static Object convertCollectionToString(Object object) {
        Collection collection = (Collection)object;
        return converter(collection.toArray());
    }

    private static Object convertDocumentToString(Object object) {
        Document doc = (Document) object;
        return converter(doc.getRootElement());
    }

    private static String convertMapToString(Object object) {
        Map map = (Map)object;
        StringBuilder sb = new StringBuilder();
        map.forEach((key, value)->{
            sb.append("key:");
            sb.append(converter(key));
            sb.append(" value:");
            sb.append(converter(value));
            sb.append(" ");
        });
        return sb.toString();
    }

3. 测试:

public static void main(String[] args) {
        List list1 = new ArrayList();
        list1.add("list1");

        HashMap<Object, Object> map1 = new HashMap<>();
        map1.put("map1", 1);
        list1.add(map1);

        JSONObject jsonObject1 = new JSONObject();
        jsonObject1.put("jsonObject1", "value");
        list1.add(jsonObject1);

        Object[] array1 = new Object[2];
        array1[0] = map1;
        array1[1] = jsonObject1;

        list1.add(array1);
        System.out.println(converter(list1));

    }

4. 测试结果:

[list1, key:map1 value:1 , key:jsonObject1 value:value , [key:map1 value:1 , key:jsonObject1 value:value ]]

你可能感兴趣的:(JAVA,java)