Java’s anonymous classes are subclasses, not instances of the class

More of a note to myself really. Anonymous classes in Java are subclasses. For whatever reason I’d led myself to believe that anonymous classes in Java are unnamed instances of classes, but they are not, they are subclasses.

this.getClass().getSimpleName() returns empty string for anonymous classes, but that doesn’t mean you can’t ever know the class name the anonymous class was created from. All you need to do is: this.getClass().getSuperclass().getSimpleName();

3 thoughts on “Java’s anonymous classes are subclasses, not instances of the class

  1. Note, you can find out if a class is an anonymous class by calling: this.getClass().isAnonymousClass();

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>