Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reflection Class.forName() finds classes <classname>$1 and <classname>$2, what are they? [duplicate]

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.

like image 906
ilomambo Avatar asked Nov 30 '25 19:11

ilomambo


1 Answers

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.

like image 173
Jon Skeet Avatar answered Dec 03 '25 12:12

Jon Skeet



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!