Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.io.BufferedWriter;
- import java.io.ByteArrayOutputStream;
- import java.io.IOException;
- import java.io.OutputStreamWriter;
- import java.io.Writer;
- import java.lang.reflect.Array;
- import java.lang.reflect.Field;
- import java.lang.reflect.Modifier;
- import java.util.Iterator;
- public class DumpToString {
- public static String dump(Object o) throws Exception {
- ByteArrayOutputStream ba = new ByteArrayOutputStream();
- Writer out = new BufferedWriter(new OutputStreamWriter(ba, "utf8"));
- out.write("dump[");
- dump(o, out, 0);
- out.write("\n]");
- out.close();
- return ba.toString();
- }
- public static void dump(Object o, Writer out, int indent) throws Exception {
- if (o == null)
- return;
- if (o.getClass().isArray()) {
- out.write("arr[");
- for (int i = 0; i < Array.getLength(o); i++) {
- if (i > 0) {
- out.write("\n");
- indent(indent+1, out);
- out.write(",");
- }
- dump(Array.get(o, i), out, indent + 1);
- }
- out.write("]");
- } else if (o instanceof Iterable) {
- Iterator i = ((Iterable) o).iterator();
- out.write("list[");
- int index = 0;
- while (i.hasNext()) {
- if (index > 0) {
- out.write("\n");
- indent(indent, out);
- out.write(",");
- }
- dump(i.next(), out, indent + 1);
- index++;
- }
- out.write("\n");
- indent(indent, out);
- out.write("]");
- } else {
- String name = o.getClass().getName();
- if (isPrimitive(name)) {
- out.write(o.toString());
- } else {
- out.write(name);
- out.write("{\n");
- indent(indent + 1, out);
- Class oClass = o.getClass();
- int i2 = 0;
- while (oClass != null) {
- if (isPrimitive(oClass.getName())) {
- if (i2 > 0) {
- out.write("\n");
- indent(indent + 1, out);
- out.write(",");
- } else
- i2++;
- out.write("toString()=" + o.toString());
- break;
- }
- Field[] fields = oClass.getDeclaredFields();
- for (int i = 0; i < fields.length; i++) {
- fields[i].setAccessible(true);
- {
- int mod = fields[i].getModifiers();
- if (Modifier.isStatic(mod) && Modifier.isFinal(mod))
- continue;
- }
- Object value = fields[i].get(o);
- if (value != null) {
- if (i2 > 0) {
- out.write("\n");
- indent(indent + 1, out);
- out.write(",");
- } else
- i2++;
- out.write(fields[i].getName());
- out.write("=");
- dump(value, out, indent + 1);
- }
- }
- oClass = oClass.getSuperclass();
- }
- out.write("\n");
- indent(indent, out);
- out.write("}");
- }
- }
- }
- private static void indent(int i, Writer out) throws IOException {
- for (; i > 0; i--)
- out.write("\t");
- }
- private static boolean isPrimitive(String name) {
- return name.startsWith("java.") || name.startsWith("javax.")
- || name.indexOf(".") < 0;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement