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

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

问题描述

最近我读到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

来自Walter Savitch的

from Walter Savitch:


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 ,包含
    anonymous内部类(本地方法 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 在一些自动生成的变量名中使用 $ :例如,此$ 0 等用于从内部类到其外部类的隐式引用。

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天全站免登陆