3

By chance I am using reflection to decode some user string entry, which can be in some case a simple integer digit (0-9) and other times it can be a call to another class methods.

While checking the string input userInput to see if a class with that name exists:

Class<?> c = Class.forName(this.getClass().getName() + "$" + userInput);

and to my surprise when the user enters "1" or "2" Class.forName() indeed finds a class with that name. This is probably basic Java, so forgive me for asking: what are those classes? I followed the code with the debugger and checked for other numbers, only 1 and 2 seem to be defined.

ilomambo
  • 8,290
  • 12
  • 57
  • 106

3 Answers3

6

Those are anonymous inner classes. For example:

public class Foo {
    public static void bar() {
        Runnable runnable = new Runnable() {
            @Override public void run() {}
        };
    }
}

This will create a class Foo$1 which implements Runnable.

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
6

They are anonymous inner classes.

If your .java file have inner/nested classes, post compilation those are generated as TheClass$xxx.class files by the compiler.

See this link for more information:

Inner class definitions produce additional class files. These class files have names combining the inner and outer class names, such as MyClass$MyInnerClass.class.

Maroun
  • 94,125
  • 30
  • 188
  • 241
1

The dollar sign is used by the compiler for inner classes.

$ sign represents inner classes. If it has a number after $ then it is an annonymous inner class. If it has a name after $ then it is only an inner class.

stinepike
  • 54,068
  • 14
  • 92
  • 112