来自Perl,我肯定错过了在源代码中创建多行字符串的“here-document”方法:

$string = <<"EOF"  # create a three-line string
text
text
text
EOF

在Java中,当我从头开始连接多行字符串时,我必须在每一行上使用繁琐的引号和加号。

有什么更好的选择吗?在属性文件中定义我的字符串?

编辑:有两个答案说StringBuilder.append()比加号更可取。谁能详细解释一下他们为什么这么想?在我看来,这一点也不可取。我正在寻找一种方法来解决多行字符串不是一级语言结构这一事实,这意味着我绝对不想用方法调用取代一级语言结构(字符串连接与加号)。

编辑:为了进一步澄清我的问题,我根本不关心性能。我关心的是可维护性和设计问题。


当前回答

这个问题有两个答案:

In you want to stick to pure Java, with Java 14 being released in March 2020, you can leverage the JEP 368 - Text Blocks, in Second Preview mode. Actually the feature is in preview mode in other releases (at least 13 has it). I created and example set here. While this feature is useful, it can be easily abused. Remember that Java requires compilation - having large character arrays in your code can be an easy way to shoot yourself in the leg (if you want a quick change, you will need recompilation - that toolset might not be available to the guy operating your application).

根据我的经验,建议在配置文件中保留大字符串(通常是应用程序操作员可以/应该在运行时更改的字符串)。

总结:负责地使用文本块:)。

其他回答

    import org.apache.commons.lang3.StringUtils;

    String multiline = StringUtils.join(new String[] {
        "It was the best of times, it was the worst of times ", 
        "it was the age of wisdom, it was the age of foolishness",
        "it was the epoch of belief, it was the epoch of incredulity",
        "it was the season of Light, it was the season of Darkness",
        "it was the spring of hope, it was the winter of despair",
        "we had everything before us, we had nothing before us",
        }, "\n");

我建议使用ThomasP所建议的实用程序,然后将其链接到构建过程中。仍然存在一个外部文件以包含文本,但在运行时不读取该文件。 工作流程如下:

构建一个“文本文件到java代码”实用程序并检查到版本控制 在每次构建时,针对资源文件运行实用程序以创建修改后的java源 Java源代码包含类似于 类TextBlock{…后面跟着一个从资源文件自动生成的静态字符串 用剩下的代码构建生成的java文件

一个不错的选择。

import static some.Util.*;

    public class Java {

        public static void main(String[] args) {

            String sql = $(
              "Select * from java",
              "join some on ",
              "group by"        
            );

            System.out.println(sql);
        }

    }


    public class Util {

        public static String $(String ...sql){
            return String.join(System.getProperty("line.separator"),sql);
        }

    }

我所知道的唯一方法是用加号连接多行

这看起来可能有点疯狂,但由于这里文档是单行声明的语法糖,并转义了换行符,因此可以为Java文件编写预处理程序,在预处理期间将这里文档更改为单行。

这需要在编译阶段(对于ant/maven构建)之前为预处理文件编写适当的插件,并为IDE编写插件。

从意识形态的观点来看,它与f.g.没有什么不同。“泛型”,这也是一种预处理的语法加糖铸造。

然而,这是一个大量的工作,所以我会在你的地方只使用.properties文件。