Friday, October 17, 2008

Multi-line String Literals in Java

I've implemented multi-line strings for Java using a library approach. The following code:

 public static void main(String[] args) {
   System.out.println(S(/*
      Wow, we finally have
      multiline strings in
      Java! HOOO!
    */));
 }
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 doesn'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 (Edit : or just use Xtend).