Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

//package com.java2s;

import java.lang.reflect.Method;

import java.util.Collection;

public class Main {
    public static <T> String toXml(T t) {
        return toXml(t, "xml");
    }

    private static <T> String toXml(T t, String head) {
        if (null == t) {
            return "";
        }
        StringBuilder sb = new StringBuilder();
        sb.append(String.format("<%s>", head)).append("\n");
        if (t instanceof Collection<?>) {
            Collection<?> collection = (Collection<?>) t;
            for (Object object : collection) {
                sb.append(toXml(object, "item"));
            }
        } else {
            Class<?> clazz = t.getClass();
            Method[] methods = clazz.getMethods();
            try {
                for (Method method : methods) {
                    String methodName = method.getName();
                    if (methodName.startsWith("get")) {
                        String key = methodName.substring(3);
                        Method setMethod = null;
                        try {
                            setMethod = clazz.getMethod("set" + key, method.getReturnType());
                        } catch (Exception e) {
                            // TODO: handle exception
                        }
                        if (null != setMethod) {
                            Object value = method.invoke(t);
                            if (method.getReturnType() == String.class) {
                                try {
                                    String stringValue = (String) method.invoke(t);
                                    if (null != stringValue) {
                                        try {
                                            Integer.parseInt(stringValue);
                                            sb.append(String.format("<%s>%s</%s>\n", key, stringValue, key));
                                        } catch (Exception e) {
                                            sb.append(String.format("<%s><![CDATA[%s]]></%s>\n", key, stringValue,
                                                    key));

                                        }
                                    }
                                } catch (Exception e) {
                                    e.printStackTrace();
                                }
                            } else {
                                sb.append(toXml(value, key));
                            }
                        }
                    }
                }
            } catch (Exception e1) {
                e1.printStackTrace();
            }
        }
        sb.append(String.format("</%s>\n", head));
        return sb.toString();
    }
}