Recently I read that the sign $ is allowed in Java variable names, but has a special meaning. Unfortunately it isn't mentioned what this special meaning is.
Therefore I ask here: What is the special meaning of $ in variable names in Java?
Here is the exact quote from
Java: A开发者_高级运维n Introduction to Problem Solving and Programming
from Walter Savitch:
Java does allow the dollar sign symbol $ to appear in an identifier, but these identifiers have a special meaning, so you should not use the $ symbol in your identifiers.
$
is used internally by the compiler to decorate certain names. Wikipedia gives the following example:
public class foo {
class bar {
public int x;
}
public void zark () {
Object f = new Object () {
public String toString() {
return "hello";
}
};
}
}
Compiling this program will produce three .class files:
foo.class
, containing the main (outer) classfoo
foo$bar.class
, containing the named inner classfoo.bar
foo$1.class
, containing the anonymous inner class (local to methodfoo.zark
)
All of these class names are valid (as $
symbols are permitted in the JVM specification).
In a similar vein, javac
uses $
in some automatically-generated variable names: for example, this$0
et al are used for the implicit this
references from the inner classes to their outer classes.
Finally, the JLS recommends the following:
The
$
character should be used only in mechanically generated source code or, rarely, to access preexisting names on legacy systems.
There is no special meaning for a $
in a variable’s name.
While technically allowed, starting the variable name with a dollar sign goes against convention, generally used only by code-generators.
To quote the Java Tutorial by Oracle:
Variable names are case-sensitive. A variable's name can be any legal identifier — an unlimited-length sequence of Unicode letters and digits, beginning with a letter, the dollar sign "$", or the underscore character "_". The convention, however, is to always begin your variable names with a letter, not "$" or "_". Additionally, the dollar sign character, by convention, is never used at all. You may find some situations where auto-generated names will contain the dollar sign, but your variable names should always avoid using it. A similar convention exists for the underscore character; while it's technically legal to begin your variable's name with "_", this practice is discouraged. White space is not permitted.
精彩评论