开发者

Java String vs. Command Line Argument

开发者 https://www.devze.com 2023-03-22 03:07 出处:网络
Why does it happen that a command line argument passed to a Java class seems to be automagically escaped while in an instantiated String object the escape character () is seemingly ignored.

Why does it happen that a command line argument passed to a Java class seems to be automagically escaped while in an instantiated String object the escape character () is seemingly ignored.

For example, if start with a string like this:

SELECT * FROM my_table WHERE my_col like 'ABC_\' ESCAPE '\'

And I try running it through a simple class like this:

public class EscapeTest {
    public static void main (String[] args) {
        String str = "SELECT * FROM my_table WHERE " 
   开发者_如何学JAVA                  + "my_col like 'ABC_\' ESCAPE '\'";
        System.out.println("ARGS[0]: "+args[0]);
        System.out.println("STR: "+str);
}
}

and I pass the "SELECT" statement above in as a command line arg, I get output that looks like this:

ARGS[0]: SELECT * FROM my_table WHERE my_col like 'ABC_\' ESCAPE '\'

STR: SELECT * FROM my_table WHERE my_col like 'ABC_' ESCAPE ''

If I look at the value of ARGS[0] in the Eclipse debugger I see that the slashes are escaped. Why does this happen? Makes it kind of hard to predict I think.


The contents of your string str does not contain any backslashes. Those are being handled by the Java compiler understanding the escape sequences of Java string literals.

The command line processor presumably isn't doing that - it's not treating backslash specially in any way, although this will depend on your shell. (In most Unix shells it would treat backslash differently. My guess is that you're on Windows.)

So, your command line argument does have backslashes in. They haven't been escaped by the executing Java process - they're just "there" in the string.

Now it sounds like the debugger is escaping the string when it's displaying it to you, so that you can see things like tabs and newlines. It's important to understand that this is just the way the debugger displays the string - there's no such thing as an "escape" within a Java string itself.

EDIT: As per comment:

To express this string in Java source code, you have to escape the backslashes:

String str = "SELECT * FROM my_table WHERE my_col like 'ABC_\\' ESCAPE '\\'"; 

Backslashes have to be escaped as backslash is the escape character in Java string literals.

0

精彩评论

暂无评论...
验证码 换一张
取 消