为什么getClass返回类的名称+ $ 1(或$ *) [英] Why getClass returns the name of the class + $1 (or $*)

查看:73
本文介绍了为什么getClass返回类的名称+ $ 1(或$ *)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一段代码,如果它是某个类的实例,则必须在其中强制转换.

I'm writing a piece of code in which I have to cast an Object if it is an instance of a certain class.

通常,我使用 instanceof 来检查兼容性.

As usual I'm using instanceof for checking the compatibility.

问题在于,由于对象属于奇怪"类,因此永远无法满足检查要求.

The problem is that the check is never satisfied because the objects belong to "strange" classes.

例如;当我在此对象上调用方法 getClass().getSimpleName()时,它将向我返回类的名称+ $ * (例如, ViewPart $ 1 >而不是 ViewPart ).

For example; when I call the method getClass().getSimpleName() on this object it return me the name of the class + $* (e.g. ViewPart$1 instead of ViewPart).

$ * 是什么意思?有解决方案或解决方法吗?

What does this $* means? Is there a solution or a workaround?

推荐答案

它显示一个内部类(匿名(如果有数字)或命名).例如:

That shows an inner class (either anonymous (if it has a number) or named). For example:

class Foo {
    static class Bar {
    }
}

Foo.Bar 的名称是 Foo $ Bar .现在,如果我们有:

The name of class Foo.Bar is Foo$Bar. Now if we had:

class Foo {

    static void bar() {
        Runnable r = new Runnable() {
            public void run() {};
        };

        System.out.println(r.getClass());
    }
}

这将打印 Foo $ 1 .

您可以在用javac创建的类文件的命名中看到相同的效果.

You can see the same effect in the naming of the class files created by javac.

这篇关于为什么getClass返回类的名称+ $ 1(或$ *)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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