Those who have used python should know that multiple lines of strings can be defined in python, which can be written like this:

multiline_str="""
first row
second line
...

"""

Looks great, other languages ​​like javascript have similarities:

let multiline_str=`
first row
second line
...

`

However, our own java has no such syntax! So in Java you can only write "multi-line" strings like this:

      String multiline_str="first line \n" +
                "Second line \n" +
                "...";

Look at how much… very silly feeling! (a bunch of newline and +)

Can it really only compromise this way? Do not!

Please see the implementation below:

![](/wp-content/uploads/2018/09/java multi-line string demo.gif)

Online code demo address: http://codingair.com/ex/code2.html?t=1535091572137&interface=146&projectId=17

Yes, you are not mistaken, it is indeed a "multi-line string" function implemented in java multi-line comments, this is a trick (small trick, not compiler level implementation), but it is very practical!

Imagine if your sql can be written like this:

Think again, you can write shell commands directly like this:

Everything is too cool, there are wood!

You can experience more features at this site: [http://codingair.com] (http://codingair.com)

Secret moment!

So how is this small trick implemented? Directly attach the source code of the S function in the above example:

/**
     * Multi-line string
     * Into the parentheses, use /* ....* / form comments
     *
     * @return
     */
    Public static String S() {
        String javaSource = threadLocal.get();
        Try {
            StackTraceElement element = new RuntimeException().getStackTrace()[1];
            Byte[] bytes = javaSource.getBytes("UTF-8");
            String s = convertStreamToString(new ByteArrayInputStream(bytes, 0, bytes.length), element.getLineNumber());
            Return s.substring(s.indexOf("/*") + 2, s.indexOf("*/"));
        } catch (Exception e) {
            e.printStackTrace();
        }

        Return null;
    }

Explain that you will notice that the first line of the function has such a line of code:

String javaSource = threadLocal.get();

That’s right, here is the source code for the class in which the S function is called, passed through the ThreadLocal object.

At this point, is there a feeling of great understanding? ! You can go to this website to experience more features: https://lambda.zhouzhipeng.com/ If you have any questions or concerns, please leave a comment below the blog.

Last modified: 2019年3月29日

Author

Comments

Write a Reply or Comment

Your email address will not be published.