Why getClass returns class name + $ 1 (or $ *)

I am writing a piece of code in which I must use Object if it is an instance of a particular class.

As usual, I use instanceof to check compatibility.

The problem is that validation is never performed because the objects belong to the "weird" classes.

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

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

+7
source share
3 answers

This shows the inner class (either anonymous (if it has a number) or a named one). For example:

 class Foo { static class Bar { } } 

The class name 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()); } } 

This will print Foo$1 .

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

+14
source

These are examples of an anonymous class. ViewPart$1 is the first anonymous class defined inside ViewPart - but that does not mean that it is a subclass of ViewPart . This is most likely an anonymous implementation of some Listener interface.

+4
source

$ stands 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 files of the class TopClass.class and TopClass $ SubClass.class.

Check the ViewPart class to see if it has any inner classes. Hope this helps.

+1
source

All Articles