Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

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 + $* (e.g. ViewPart$1 instead of ViewPart).

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

like image 431
Maverik Avatar asked Aug 24 '11 08:08

Maverik


People also ask

What is returned from the getClass () method of the object class?

The Java Object getClass() method returns the class name of the object.

What is $1 Java class file?

The $1 are anonymous inner classes you defined in your WelcomeApplet. java file. e.g. compiling public class Run { public static void main(String[] args) { System.out.println(new Object() { public String toString() { return "77"; } }); } private class innerNamed { } }

What does the getClass method return in Java?

getClass() method returns the runtime class of an object. That Class object is the object that is locked by static synchronized methods of the represented class.

What is getClass () getName () in Java?

Java Class getName() Method The getName() method of java Class class is used to get the name of the entity, and that entity can be class, interface, array, enum, method, etc. of the class object. Element Type.


3 Answers

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. 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.

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

like image 65
Jon Skeet Avatar answered Sep 19 '22 06:09

Jon Skeet


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. It's most likely an anoymous implementation of some Listener interface.

like image 22
Michael Borgwardt Avatar answered Sep 20 '22 06:09

Michael Borgwardt


$ 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.

Check your ViewPart class whether it has any inner classes. Hope it helps.

like image 33
Kishore DVS Avatar answered Sep 21 '22 06:09

Kishore DVS