Friday, October 17, 2008

Multi-line String Literals in Java

Having multi-line string literals is a common and useful thing in most modern languages. It is for instance very convenient to use multi-line strings to specify test data in-line as opposed to referring to external files containing the data. As Java lackes multi-line string literals, one observes the definition of data in external files very often.

I've implemented multi-line strings in Java using a library approach, so that it's possible to write the following:

/**
* @param args
*/
public static void main(String[] args) {
System.out.println(S(/*
Wow, we finally have
multiline strings in
Java! HOOO!
*/));
}

which will print the following to standard out:

Wow, we finally have
multiline strings in
Java! HOOO!


How does this work?
Well, first of all you have to make sure that your source is on the class path, then the following code does the job:

public static String S() {
StackTraceElement element = new RuntimeException().getStackTrace()[1];
String name = element.getClassName().replace('.', '/') + ".java";
InputStream in = getClassLoader().getResourceAsStream(name);
String s = convertStreamToString(in, element.getLineNumber());
return s.substring(s.indexOf("/*")+2, s.indexOf("*/"));
}

Obviously this don't perform that well, but for unit testing it's sufficient.
Maybe it would be cool to add some support for interpolation functionality to it (using e.g. groovy or Xpand).