$ symbol in .class files

class, java

Solution

They are anonymous inner classes. In other words, when you have a piece like

class OuterClass {
    // ...
    void method() {
        Thread t = new Thread(new Runnable() { 
            // ... code implementing Runnable interface ... 
        });
        // ... code to use t or whatever
    }
}

That generates anonymous inner class, in this case implementing the `Runnable` interface, and compiled code of that class goes to a `OuterClass$<number>.class` file. You can have more than one such class, with increasing number in the .class file name.

Note that syntax is exactly the same even if you extend a class with the anonymous inner class, instead of implementing an interface. This is a slightly different from creating named classes, where you need to use `implements` and `extends` as appropriate.

Problem

I have a program called `MyProgram.java`. I want to run it from different directory which will be run on another machine. So I made a directory and copied `MyProgram.class` file and made a `.bat` file that runs it (`Run.bat`) which includes the command: `@java MyProgram`. This didn't work, I had to copy `SPVerification$1.class` that was generated from `Eclipse` in order to make it work. What is this `XXX$1.class` files and why do I need them beside the `XXX.class` file in order to run an application?

Original source