不久前,我遇到了字符串中不可見字符的問題。 因為它們是不可見的,所以它們確實會引起混亂。
String a = "Hello\u200e";String b = "Hello\u200f";System.out.println('\'' + a + "' and '" + b + "' are length "+ a.length() + " and " + b.length() + ", equals() is " + a.equals(b));
版畫
'Hello?' and 'Hello?' are length 6 and 6, equals() is false
不可見的標識符
想象一下我對發現您可以在Java:P中的標識符中使用不可見字符的反應。 這些字符不能出現在Java標識符的開頭,但可以出現在其他任何位置。
System.out.println("String _\u200e = \"Hello \";");System.out.println("String _\u200f = \"World\";");System.out.println("String _\u200e\u200f = \" !!\";");System.out.println("System.out.println(_\u200e+_\u200f+_\u200e\u200f);");
版畫
String _? = "Hello ";
String _? = "World";
String _?? = " !!";
System.out.println(_?+_?+_??);
運行時打印
Hello World !!
因此,我們有三個標識符都顯示相同的標識符,因為它們的名稱中具有不同的不可見字符!
令人驚訝的是,此代碼編譯,運行并打印了可能在標識符中但未啟動的所有字符。 該代碼包含\ u202e ,它確實使代碼的顯示混亂。
for (char c??h = 0; c??h < Character.MAX_VALUE; c??h++)if (Character.isJavaIdentifierPart(c??h) && !Character.isJavaIdentifierStart(c??h))System.out.printf("%04x <%s>%n", (int) c??h, "" + c??h);
參考: Vanilla Java博客上來自我們的JCG合作伙伴 Peter Lawrey的隱藏代碼 。
翻譯自: https://www.javacodegeeks.com/2012/09/java-hidden-code.html