Java 编译的类包含美元符号

我一直在使用 Eclipse 作为我的 IDE。我还使用它将应用程序导出到一个 JAR 文件中。当我查看 JAR 文件中的类时,我的一些类包含该类的名称、一个美元符号和一个数字。例如:

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

我注意到在更大的课堂上会这样。这是因为类变得太大了,它会将其编译成多个类吗?我已经在多个论坛上谷歌和搜索了 Java 文档,但是没有找到任何与之相关的东西。有人能解释一下吗?

55714 次浏览

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

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.

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.