Java multiline string

前端 未结 30 2905
醉梦人生
醉梦人生 2020-11-22 15:55

Coming from Perl, I sure am missing the \"here-document\" means of creating a multi-line string in source code:

$string = <<\"EOF\"  # create a three-l         


        
30条回答
  •  执念已碎
    2020-11-22 16:26

    This is an old thread, but a new quite elegant solution (with only 4 maybe 3 little drawbacks) is to use a custom annotation.

    Check : http://www.adrianwalker.org/2011/12/java-multiline-string.html

    A project inspired from that work is hosted on GitHub:

    https://github.com/benelog/multiline

    Example of Java code:

    import org.adrianwalker.multilinestring.Multiline;
    ...
    public final class MultilineStringUsage {
    
      /**
      
        
        
          

    Hello
    Multiline
    World

    */ @Multiline private static String html; public static void main(final String[] args) { System.out.println(html); } }

    The drawbacks are

    1. that you have to activate the corresponding (provided) annotation processor.
    2. that String variable can not be defined as local variable Check Raw String Literals project where you can define variables as local variables
    3. that String cannot contains other variables as in Visual Basic .Net with XML literal (<%= variable %>) :-)
    4. that String literal is delimited by JavaDoc comment (/**)

    And you probably have to configure Eclipse/Intellij-Idea to not reformat automatically your Javadoc comments.

    One may find this weird (Javadoc comments are not designed to embed anything other than comments), but as this lack of multiline string in Java is really annoying in the end, I find this to be the least worst solution.

提交回复
热议问题