简体   繁体   English

为什么 getClass 返回类名 + $1(或 $*)

[英]Why getClass returns the name of the class + $1 (or $*)

I'm writing a piece of code in which I have to cast an Object if it is an instance of a certain class.我正在编写一段代码,如果它是某个类的实例,我必须在其中强制转换一个对象。

As usual I'm using instanceof for checking the compatibility.像往常一样,我使用instanceof来检查兼容性。

The problem is that the check is never satisfied because the objects belong to "strange" classes.问题是检查永远不会满足,因为对象属于“奇怪的”类。

For example;例如; when I call the method getClass().getSimpleName() on this object it return me the name of the class + $* (eg ViewPart$1 instead of ViewPart ).当我在这个对象上调用getClass().getSimpleName() ,它会返回类的名称 + $* (例如ViewPart$1而不是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 {
    }
}

The name of class Foo.Bar is Foo$Bar . Foo.Bar类的名称是Foo$Bar Now if we had:现在,如果我们有:

class Foo {

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

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

That will print Foo$1 .这将打印Foo$1

You can see the same effect in the naming of the class files created by javac.您可以在 javac 创建的类文件的命名中看到相同的效果。

These are instances of an anonymous class .这些是匿名类的实例。 ViewPart$1 is the first anonymous class defined inside ViewPart - but that doesn't mean it's a subclass of ViewPart . ViewPart$1是在ViewPart定义的第一个匿名类 - 但这并不意味着它是ViewPart的子类。 It's most likely an anoymous implementation of some Listener interface.它很可能是某个 Listener 接口的匿名实现。

$ denotes for inner class. $ 表示内部类。 For example consider two classes例如考虑两个类

public class TopClass {
  class SubClass {
     // some methods
  }// inner class end
} // outer class end

If you compile this code you will get two class files TopClass.class and TopClass$SubClass.class.如果编译此代码,您将获得两个类文件 TopClass.class 和 TopClass$SubClass.class。

Check your ViewPart class whether it has any inner classes.检查您的 ViewPart 类是否有任何内部类。 Hope it helps.希望能帮助到你。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM