为什么
Java变量名中不允许使用特殊字符($,_除外)?
解决方法
情况并非如此 – 许多特殊字符对于标识符实际上是有效的.定义为
in the JLS #3.8:
An identifier is an unlimited-length sequence of Java letters and Java digits,the first of which must be a Java letter.
[…]
A “Java letter” is a character for which the methodCharacter.isJavaIdentifierStart(int)
returns true.
A “Java letter-or-digit” is a character for which the methodCharacter.isJavaIdentifierPart(int)
returns true.
例如,这是一个有效的变量名:
String sçèêûá¢é£¥ = "bc";
您可以使用这个简单的代码查看所有有效的字符:
public static void main(String args[]) { for (int i = 0; i < Character.MAX_VALUE; i++) { if (Character.isJavaIdentifierPart(i)) { System.out.println("i = " + i + ": " + (char) i); } } }
ps:很好的例子on @PeterLawrey’s blog