The javac compiler has some code like this:
/**
* Escapes each character in a string that has an escape sequence or
* is non-printable ASCII. Leaves non-ASCII characters alone.
*/
public static String quote(String s) {
StringBuilder buf = new StringBuilder();
for (int i = 0; i < s.length(); i++) {
buf.append(quote(s.charAt(i)));
}
return buf.toString();
}
/**
* Escapes a character if it has an escape sequence or is
* non-printable ASCII. Leaves non-ASCII characters alone.
*/
public static String quote(char ch) {
switch (ch) {
case '\b': return "\\b";
case '\f': return "\\f";
case '\n': return "\\n";
case '\r': return "\\r";
case '\t': return "\\t";
case '\'': return "\\'";
case '\"': return "\\\"";
case '\\': return "\\\\";
default:
return (isPrintableAscii(ch))
? String.valueOf(ch)
: String.format("\\u%04x", (int) ch);
}
}
/**
* Is a character printable ASCII?
*/
private static boolean isPrintableAscii(char ch) {
return ch >= ' ' && ch <= '~';
}
This code is used to "quote" strings which comes from user code, and need to be rendered exactly as they have been typed by the user.
Now that the Java SE API has the String::translateEscapes methods, it might be perhaps a good idea to make the internal javac functionality more officially supported (since it seems to be the reverse of what the newly added String method does?).
/**
* Escapes each character in a string that has an escape sequence or
* is non-printable ASCII. Leaves non-ASCII characters alone.
*/
public static String quote(String s) {
StringBuilder buf = new StringBuilder();
for (int i = 0; i < s.length(); i++) {
buf.append(quote(s.charAt(i)));
}
return buf.toString();
}
/**
* Escapes a character if it has an escape sequence or is
* non-printable ASCII. Leaves non-ASCII characters alone.
*/
public static String quote(char ch) {
switch (ch) {
case '\b': return "\\b";
case '\f': return "\\f";
case '\n': return "\\n";
case '\r': return "\\r";
case '\t': return "\\t";
case '\'': return "\\'";
case '\"': return "\\\"";
case '\\': return "\\\\";
default:
return (isPrintableAscii(ch))
? String.valueOf(ch)
: String.format("\\u%04x", (int) ch);
}
}
/**
* Is a character printable ASCII?
*/
private static boolean isPrintableAscii(char ch) {
return ch >= ' ' && ch <= '~';
}
This code is used to "quote" strings which comes from user code, and need to be rendered exactly as they have been typed by the user.
Now that the Java SE API has the String::translateEscapes methods, it might be perhaps a good idea to make the internal javac functionality more officially supported (since it seems to be the reverse of what the newly added String method does?).
- csr for
-
JDK-8263253 Add String::encodeEscapes
- Draft
- is blocked by
-
JDK-8263261 Extend String::translateEscapes to support unicode escapes
- Closed