java 调试命令行参数,Java字符串与命令行参数

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 "

+ "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.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值