print_r do PHP em JAVA

Fala galera,

Gostaria de saber se há alguma forma de reproduzir o print_r do PHP em JAVA, seria de muita ajuda.

Vlw.

Uma forma meio tosca de fazer isso, e que não funciona para arrays de tipos primitivos, é usar Arrays.asList. Exemplo:

String[] x = {"abc", "def", "ghi"};
System.out.println (Arrays.asList (x)); // imprime [abc, def, ghi]

Se quiser algo mais estruturado, você mesmo tem de fazer (infelizmente).

Poxa, isso é mal.

Mas eu já li em outros lugares que o pessoal faz com Reflector. O que é isso e como se usa?

É, você pode tentar usar reflection (não “Reflector” que é o nome de um pacote do .NET ( http://www.red-gate.com/products/reflector/ ) que permite olhar dentro de DLLs e EXEs .NET). É um bocadinho trabalhoso; alguém já deve ter feito isso, porque convenhamos, é bem chatinho para fazer.

[code]package teste;

import java.lang.reflect.;
import java.math.
;
import java.util.*;

public class RecursiveDump {
/** How many characters to indent. */
private static final int INDENT = 4;

/** Default constructor. */
private RecursiveDump() {
//empty constructor
}

/**

  • Dump an Object, indented of a certain amount of characters.
  • @param obj
  • the object to be dumped
  • @param indent
  • how many characters to indent
  • @return a String representation of the Object
    */
    public static String dump(final Object obj) {
    return dump(obj, 0);
    }

public static String dumpHtml(final Object obj) {
StringBuilder res = new StringBuilder();
res.append("");
res.append(dump(obj, 0).replaceAll("\n", “
”).replaceAll(" “, " “)); //&_nbsp;
res.append(””);
return res.toString();
}

private static String dump(final Object obj, final int indent) {
if (obj == null) {
return “null”;
}
if (isPrimitive(obj)) {
return dump(obj.toString(), indent);
} else if (obj instanceof List<?>) {
return dump((List) obj, indent);
} else if (obj instanceof HashMap<?, ?>) {
return dump((HashMap) obj, indent);
} else if (obj instanceof String[]) {
return dump((String[]) obj, indent);
} else if (obj instanceof Date) {
return dump(((Date) obj).toGMTString(), indent);
} else if (obj instanceof Object) {
List mets = new ArrayList();
for (Method met : obj.getClass().getDeclaredMethods()) {
if (met.getName().startsWith(“get”)) {
mets.add(met);
}
}
StringBuilder res = new StringBuilder();
Integer ofset = 0;
res.append(dump(obj.getClass().getSimpleName(), 0));
res.append(":Object");
ofset = res.length() + indent;
if (mets.size() > 0) {
if (mets.size() > 1) res.append("\n").append(repeat(" “, ofset));
res.append(”(");
for (Method met : mets) {
try {
Object ret = obj.getClass().getMethod(met.getName()).invoke(obj);
if (ret == null) {
continue;
}
if (mets.size() > 1) res.append("\n").append(repeat(" “, ofset));
res.append(dump(met.getName().substring(3), 0));
res.append(” => “);
if (isPrimitive(ret)) {
res.append(dump(ret, 0));
} else {
res.append(dump(ret, ofset));
}
} catch (Exception e) {
res.append(”\n").append(repeat(" “, ofset));
res.append(“Erro: " + e.getMessage());
}
}
if (mets.size() > 1) res.append(”\n”).append(repeat(" “, ofset));
res.append(”)");
} else {
res.append("(");
res.append(dump(obj.toString(), 0));
res.append(")");
}
return res.toString();
}
return dump(obj.toString(), 0);
}

private static boolean isPrimitive(Object obj) {
if (obj instanceof String) {
return true;
} else if (obj instanceof Number) {
return true;
} else if (obj instanceof Integer) {
return true;
} else if (obj instanceof Long) {
return true;
} else if (obj instanceof Short) {
return true;
} else if (obj instanceof Double) {
return true;
} else if (obj instanceof Character) {
return true;
} else if (obj instanceof BigDecimal) {
return true;
}
return false;
}

/**

  • Dump a List of Object, indented by a certain amount of characters.
  • @param ar
  • the List of Object to dump
  • @param indent
  • how many characters to indent
  • @return a String representation of the List of Object
    */
    private static String dump(final List ar, final int indent) {
    if (ar == null) {
    return “null”;
    }
    StringBuilder res = new StringBuilder();
    res.append(“List”);
    if (ar.size() == 0) {
    res.append("(empty)");
    return res.toString();
    }
    res.append("\n").append(repeat(" “, indent));
    res.append(”(");
    Object obj;
    for (int i = 0; i < ar.size(); i++) {
    obj = ar.get(i);
    res.append("\n").append(repeat(" “, indent + INDENT));
    res.append(”[").append(i).append("] => “);
    res.append(dump(obj, indent + INDENT));
    }
    res.append(”\n").append(repeat(" “, indent));
    res.append(”)");
    return res.toString();
    }

/**

  • Dump an HashMap, indented by a certain amount of characters.
  • @param hm
  • the HashMap to be dumped
  • @param indent
  • how many characters to indent
  • @return a String representation of the HashMap
    */
    private static String dump(final Map<Object, Object> hm, final int indent) {
    Object key, value;
    if (hm == null) {
    return “null”;
    }
    StringBuilder res = new StringBuilder();
    res.append(“HashMap”);
    if (hm.size() == 0) {
    return res.append("(empty)").toString();
    }
    Set keys = hm.keySet();
    //
    res.append("\n").append(repeat(" “, indent));
    res.append(”(");
    for (Iterator it = keys.iterator(); it.hasNext():wink: {
    key = it.next();
    value = hm.get(key);
    res.append("\n").append(repeat(" “, indent + INDENT)).append(”[")
    .append(dump(key, 0)).append("] => “)
    .append(dump(value, indent + INDENT));
    }
    res.append(”\n").append(repeat(" “, indent));
    res.append(”)");
    return res.toString();
    }

/**

  • Dump an Enumeration indented a certain amount of characters.
  • @param myEnum
  • the Enumeration to dump
  • @param indent
  • how many characters to indent
  • @return a String representation of the Enumeration
    */
    private static String dump(final Enumeration myEnum, final int indent) {
    StringBuilder res = new StringBuilder();
    Object elem;
    while (myEnum.hasMoreElements()) {
    elem = myEnum.nextElement();
    res.append(repeat(" “, indent + INDENT)).append(”[")
    .append(dump(elem, indent + INDENT)).append("]\n");
    }
    return res.toString();
    }

/**

  • Dump an array of String, with a certain indentation.
  • @param ar
  • the array of String to dump
  • @param indent
  • how many characters to indent
  • @return a String representation of the String array
    */
    private static String dump(final String[] ar, final int indent) {
    StringBuilder res = new StringBuilder();
    if (indent > 0) {
    res.append(repeat(" “, indent));
    }
    if (ar == null) {
    res.append(“null”);
    return res.toString();
    }
    res.append(”[ “);
    for (int i = 0; i < ar.length; i++) {
    res.append(”’").append(ar[i]).append("’ “);
    }
    res.append(”]");
    return res.toString();
    }

private static String dump(final String ar, final int indent) {
StringBuilder res = new StringBuilder();
if (indent > 0) {
res.append(repeat(" ", indent));
}
if (ar == null) {
res.append(“null”);
} else {
res.append(ar);
}
return res.toString();
}

/**

  • Dump a Matrix of String (Array of Array).
  • @param ar
  • the matrix of String
  • @return a String representation
    */
    private static String dump(final String[][] ar) {
    StringBuilder res = new StringBuilder();
    res.append(“Array(\n”);
    for (int i = 0; i < ar.length; i++) {
    res.append(dump(ar[i], INDENT));
    if (i + 1 < ar.length) {
    res.append(",\n");
    } else {
    res.append("\n");
    }
    }
    res.append(")\n");
    return res.toString();
    }

/**

  • Dump an array of String.
  • @param ar
  • the array of String to dump
  • @return a String representation of the String array
    */
    private static String dump(final String[] ar) {
    return dump(ar, 0);
    }

/**

  • Dump an array of Integer.
  • @param ar
  • the array of Integer to dump
  • @return a String representation of the Integer array
    */
    private static String dump(final Integer[] ar) {
    StringBuilder res = new StringBuilder();
    res.append(“Array( “);
    for (int i = 0; i < ar.length; i++) {
    res.append(”[”).append(ar[i]).append("] “);
    }
    res.append(”)");
    return res.toString();
    }

/**

  • Dump an array of int.
  • @param ar
  • the array of int to dump
  • @return a String representation of the int array
    */
    private static String dump(final int[] ar) {
    StringBuilder res = new StringBuilder();
    res.append(“Array( “);
    for (int i = 0; i < ar.length; i++) {
    res.append(”[”).append(ar[i]).append("] “);
    }
    res.append(”)");
    return res.toString();
    }

/**

  • Dump an HashMap.
  • @param hm
  • the HashMap to dump
  • @return a String representation of the HashMap
    */
    private static String dump(final Map<String, Object> hm) {
    return dump(hm, 0);
    }

/**

  • Dump a List of Object.
  • @param ar
  • a List of Object
  • @return a String representation of the List.
    */
    private static String dump(final List ar) {
    return dump(ar, 0);
    }

/**

  • Dump an Enumeration.
  • @param myEnum
  • the enumeration to be dumped
  • @return a String representation of the enumeration
    */
    private static String dump(final Enumeration myEnum) {
    return dump(myEnum, 0);
    }

/**

  • Repeat input multiplier times. multiplier has to be greater than or
  • equal to 0. If the multiplier is <= 0, the function will return an
  • empty string.
  • @param input
  •            the input String
    
  • @param multiplier
  •            how many times to repeat it
    
  • @return the resulting String
    */
    private static String repeat(final String input, final int multiplier) {
    if (multiplier <= 0) {
    return “”;
    }
    StringBuilder sb = new StringBuilder();
    for (int i = 0; i < multiplier; i++) {
    sb.append(input);
    }
    return sb.toString();
    }
    }

[/code]

Object objetoQualquer = new ....

 Map<Object, Object> map = new HashMap<Object, Object>();
  map.put("Codigo", objetoQualquer);

  System.out.println(RecursiveDump.dump(map));

  System.out.println(RecursiveDump.dumpHtml(objetoQualquer));