IT TIP

java compiled classes contain dollar signs

itqueen 2020. 10. 21. 22:15
반응형

java compiled classes contain dollar signs


I've been using Eclipse as my development IDE. I also use it to export my application into a .jar file. When I look at my classes in the .jar file, a few of my classes contain the name of that class, a dollar sign, then a number. Example:

  • Find$1.class
  • Find$2.class
  • Find$3.class
  • Find.class

I've noticed it does this on bigger classes. Is this because the classes get so big, it compiles it into multiple classes? I've googled and looked on multiple forums, and search the Java Documentation but have not found anything even related to it. Could someone explain?


Inner classes, if any present in your class, will be compiled and the class file will be ClassName$InnerClassName. In case of Anonymous inner classes, it will appear as numbers. Size of the Class (Java Code) doesn't lead to generation of multiple classes.

E.g. given this piece of code:

public class TestInnerOuterClass {
    class TestInnerChild{

    }

    Serializable annoymousTest = new Serializable() {
    };
}

Classes which will be generated will be:

  1. TestInnerOuterClass.class
  2. TestInnerOuterClass$TestInnerChild.class
  3. TestInnerOuterCasss$1.class

Update:

Using anonymous class is not considered a bad practice ,it just depends on the usage.

Check this discussion on SO


This is because you have anonymous classes within this larger class. They get compiled using this naming convention.

See The Anonymous Class Conundrum


In addition to the above cases presented by @mprabhat, the other cases could be:

  1. if you class contain a enum variable a separate class would be generated for that too. The name of the .class generated would be ClassName$Name_of_enum.
  2. If your class X is inheriting i.e. extending another class Y, then there would be a .class generated with the name ClassName$1.class or ClassName$1$1.class
  3. If your class X is implementing an interface Y, then there would be a .class generated with the name ClassName$1.class or ClassName$1$1.class.

These cases are derivations of my inspection on .class files in jar.


To answer your comment about are anonymous classes bad. They are most definately not. Consider this to assign an action listener to a JButton:

JButton button = new JButton(...);
button.addActionListener(new ActionListener() { ... });

or this to do a case insensitive sort by the "name" property

Collections.sort( array, new Comparator<Foo>() {
    public int compare(Foo f1, Foo f2) {
        return f1.getName().toLowerCase().compareTo(f2.getName().toLowerCase());
    }
});

You'll also see a lot of Runnable and Callable done as anonymous classes.

참고URL : https://stackoverflow.com/questions/11388840/java-compiled-classes-contain-dollar-signs

반응형