匿名类型的类型 [英] Type of anonymous type

查看:97
本文介绍了匿名类型的类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我遇到的一个有趣的小事。我正在搞乱匿名类型,我写了如下:

This is an interesting little thing I've encountered. I was messing around with anonymous types and I wrote something like:

public class Test {
    public static void method(Object obj) {
        System.out.println(obj.getClass().getName());
    }

    public static void main(String[] args) {
        method(new Object() {
           int n = 0; 
        });
    }
}

当我打印的结果是实际上 test.Test $ 1 这是定义匿名对象的类的名称(如果您将打印类型名称的方法移动到另一个对象,它仍然是相同的类)。

Well, I was quite surprised when the result printed was in fact test.Test$1 which is the name of the class in which the anonymous object was defined (it's still the same if you move the method that prints the type name to another class).

有人可以解释这种行为吗?这是在Java标准中指定还是另一个未定义的行为?

Can someone explain this behavior? Is this specified in the Java standard or is yet another "undefined behavior"?

推荐答案

打印出的类名具有尾随 $ 1 。内部类总是通过连接 $ 命名,内部类名称包含类'name。匿名类只是获取一个数字而不是一个名称。有效地,打印输出的类名称是test.Test中包含的第一个匿名类。

If you look again, you'll see that the class name printed out has a trailing $1. Inner classes always get named by concatenating $ and the inner class name to the containing class' name. Anonymous classes simply get a number instead of a name. So effectively, the class name that's getting printed out is saying "the first anonymous class contained in test.Test".

这篇关于匿名类型的类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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