Java 注释也会被执行?

Java About 1,428 words

代码

public class Comment {

    public static void main(String[] args) {
        String str = "你好世界";
        // \u000dstr="Hello World";
        System.out.println(str);
    }

}

输出:

Hello World

原因

查看反编译.class后的代码。发现编译器将\u000d后的注释换了一行,发现是\u000d对应的是Unicode中的换行符,即\r。因为Java支持Unicode进行编码(毫无可读性可言),所以编译器再处理Unicode时先转换字符。

public class Comment {
    public Comment() {
    }

    public static void main(String[] args) {
        String str = "你好世界";
        str = "Hello World";
        System.out.println(str);
    }
}

延伸

虽然以下代码在IDEA中会提示错误信息:Cannot resolve symbol 'u000d',但不影响正常执行。

public static void main(String[] args) {
    System.out.println(\u000d);
    System.out.println('\u03C0');

    double π = Math.PI;
    System.out.println(\u03C0);
}

输出以下信息,发现变量π,可以用Unicode码中的\u03c0代替并正常输出Math.PI的值。


π
3.141592653589793

注意

将注释中的变量名str改为str2,编译时将得到以下错误信息:

Error:(8, 18) java: 找不到符号
  符号:   变量 str2
  位置: 类 Comment

结论

Java中的注释是肯定不会被执行的,只是编译器识别了\u000d转换成了换行符,将注释拆成了两句语句。

相关类

JDKlib包下的tools.jarIDEA可以在Project Structure中的Libraries中添加。

com.sun.tools.javac.parser.UnicodeReader

com.sun.tools.javac.parser.JavacParser

完整代码

public class Comment {

    public static void main(String[] args) {
        String str = "你好世界";
        // \u000dstr="Hello World";
        System.out.println(str);

        System.out.println(\u000d);
        System.out.println('\u03C0');

        double π = Math.PI;
        System.out.println(\u03C0);
    }

}
Views: 2,414 · Posted: 2020-05-05

————        END        ————

Give me a Star, Thanks:)

https://github.com/fendoudebb/LiteNote

扫描下方二维码关注公众号和小程序↓↓↓

扫描下方二维码关注公众号和小程序↓↓↓


Today On History
Browsing Refresh