Is there a Java method that works like Python\'s repr? For example, assuming the function were named repr,
\"foo\\n\\tbar\".repr()
would re
It appears that Jython already does this. You could, in theory, include the Jython jar, startup an interpreter, and actually run repr(object) on the object in question. Probably more overhead than you want, but does exactly what you describe.
If you want to embed the Jython interpreter in your application, consider http://wiki.python.org/jython/JythonFaq/EmbeddingJython .
In case you are using Groovy, it provides a similar StringEscapeUtils class as Apache Commons Lang:
StringEscapeUtils.escapeJava("foo\n\tbar")
If you're only going to be using this on strings, in a pinch you could just write a method that goes through the string and replaces special characters (for whatever definition of "special" you want) with their escape codes. That's what I would do. (I did a quick search and nothing came up on Google, so it might be faster to just write the method than to hunt for an existing implementation)
This will do it, but it's a bit of a hack, it uses StringUtils and replaceEach from Common Lang to achieve a simple replace:
String hello = "hello\n\tworld\n\n\t";
String replaced = StringUtils.replaceEach(hello, new String[] {"\n", "\t", "\r", "\f"},
new String[] {"\\n", "\\t", "\\r", "\\f"});
System.out.println("Replaced " + replaced);
don't think there's a specific method -- but this'll solve it without commons lang:
public class test {
public test() throws Exception {
byte[] hello = "hello\n\tworld\n\n\t".getBytes();
System.out.println(new String(hexToByte(stringToHex(hello).replaceAll("0a", "5c6e")
.replaceAll("09", "5c74"))));
}
public static void main(String[] args) throws Exception {
new test();
}
public static String stringToHex(byte[] b) throws Exception {
String result = "";
for (int i = 0; i < b.length; i++) {
result += Integer.toString((b[i] & 0xff) + 0x100, 16).substring(1);
}
return result;
}
public static byte[] hexToByte(String s) {
int len = s.length();
byte[] data = new byte[len / 2];
for (int i = 0; i < len; i += 2) {
data[i / 2] = (byte) ((Character.digit(s.charAt(i), 16) << 4) + Character.digit(s.charAt(i + 1), 16));
}
return data;
}
}
If there were such a method, it would make writing quines in Java really easy, because it would solve the problem of escaping the quotes. Seeing as the simplest quines in Java all require manually inserting the quote character manually with its character code, it is unlikely that such a method exists.