变量名中的$是什么意思? [英] What is the meaning of $ in a variable name?

查看:51
本文介绍了变量名中的$是什么意思?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

最近我读到在 Java 变量名中允许使用 $ 符号,但它具有特殊含义.遗憾的是没有提到这个特殊含义是什么.

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.

所以我在这里问:Java中变量名中$的特殊含义是什么?

Therefore I ask here: What is the special meaning of $ in variable names in Java?

这是来自

Java:问题解决和编程简介

Java: An Introduction to Problem Solving and Programming

来自沃尔特·萨维奇:

Java 确实允许美元符号 $ 出现在标识符中,但是这些标识符有特殊的意义,所以你不应该使用标识符中的 $ 符号.

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";
            }
        };
    }
}

编译这个程序会产生三个.class文件:

Compiling this program will produce three .class files:

  • foo.class,包含主(外)类foo
  • foo$bar.class,包含命名的内部类 foo.bar
  • foo$1.class,包含匿名内部类(本地于方法 foo.zark)
  • foo.class, containing the main (outer) class foo
  • foo$bar.class, containing the named inner class foo.bar
  • foo$1.class, containing the anonymous inner class (local to method foo.zark)

所有这些类名都是有效的(因为 $ 符号在 JVM 规范中是允许的).

All of these class names are valid (as $ symbols are permitted in the JVM specification).

与此类似,javac 在一些自动生成的变量名中使用了$:例如,this$0 等用于从内部类到外部类的隐式 this 引用.

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.

最后,JLS 推荐以下:

$ 字符只能在机械生成的源代码中使用代码,或者在极少数情况下访问旧系统上预先存在的名称.

The $ character should be used only in mechanically generated source code or, rarely, to access preexisting names on legacy systems.

这篇关于变量名中的$是什么意思?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆