There has been an long outstanding request for
multiline stings in java. See http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4472509
and http://www.mrchucho.net/index.php/archives/2005/06/01/multi-line-strings-in-java/
With all the new 1.5 stuff being added - annotations, printf, varargs
it is quite annoying that java still has to do
"aaa\n"
+ "bbb\n"
...
for multiline strings.
There is especially annoying when - writing unit tests (xml strings for example)
and for doc and SQL annotations.
With JSR Scripting being added in jdk6, it has become completely stupid,
It would be nice to something like the pythonic -
engine = manager.getEngineByName("beanshell");
engine.eval("""
map = new HashMap();
map.put("foo", "bar");
importObject( map );
print( get("foo") ); // bar
""");
With the GPL release of javac, one can have a look at the
javac code - and see what needs to be done to add this much
needed extension.
A quick look at the code shows that it should be relatively easy
to add this - but I do not have the time at the moment
to add """.
However, one can add multiline strings easily
by relaxing the check for NL and CR.
$COMPILER_HOME/src/share/classes/com/sun/tools/javac/parser/Scanner.java
Line: 916 Change to
while (ch != '\"' /*&& ch != CR && ch != LF*/ && bp < buflen)
and presto the following compiles:
public class HelloWorld {
public static void main(String[] args) {
System.out.println("
Hello world
");
}
}
/f/src/compiler > java -jar dist/lib/javac.jar HelloWorld.java
/f/src/compiler > java -cp . HelloWorld
Hello world
/f/src/compiler >
The script example is a little ropy as one needs to escape
the " and \.
import javax.script.*;
public class ScriptExample {
public static void main(String[] args) throws Exception {
ScriptEngineManager m = new ScriptEngineManager();
ScriptEngine engine = m.getEngineByName("javascript");
engine.eval("
print(\"This is the world \");
print(\"calling\\n\");
");
}
}
/f/src/compiler > java -jar dist/lib/javac.jar ScriptExample.java
/f/src/compiler > java -cp . ScriptExample
This is the world calling
/f/src/compiler >