为什么带有内部类的 Java 代码会生成第三个 SomeClass$1.class 文件?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/380406/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Why does Java code with an inner class generates a third SomeClass$1.class file?
提问by Johan
If I have an inner class, like this:
如果我有一个内部类,就像这样:
public class Test
{
public class Inner
{
// code ...
}
public static void main(String[] args)
{
// code ...
}
}
When I compile it, I expect it should generate two files:
当我编译它时,我希望它应该生成两个文件:
Test.class
Test$Inner.class
So why do I sometimes see classfiles like SomeClass$1.class, even though SomeClass does not contain an inner class called "1"?
那么为什么我有时会看到像 SomeClass$1.class 这样的类文件,即使 SomeClass 不包含名为“1”的内部类?
回答by hhafez
回答by waltwood
You'll also get something like SomeClass$1.classif your class contains a private inner class (not anonymous) but you instantiate it at some point in the parent class.
SomeClass$1.class如果您的类包含一个私有内部类(非匿名),但您在父类中的某个点实例化它,您也会得到类似的结果。
For example:
例如:
public class Person {
private class Brain{
void ponderLife() {
System.out.println("The meaning of life is...");
}
}
Person() {
Brain b = new Brain();
b.ponderLife();
}
}
This would yield:
这将产生:
Person.class
Person$Brain.class
Person.class
Personally I think that's a bit easier to read than a typical anonymous class especially when implementing a simple interface or an abstract class that only serves to be passed into another local object.
我个人认为这比典型的匿名类更容易阅读,尤其是在实现简单接口或仅用于传递给另一个本地对象的抽象类时。
回答by Jean
to build up on hhafez : SomeClass$1.class represents anonymous inner classes. An example of such a class would be
建立在 hhafez 上: SomeClass$1.class 代表匿名内部类。这种类的一个例子是
public class Foo{
public void printMe(){
System.out.println("redefine me!");
}
}
public class Bar {
public void printMe() {
Foo f = new Foo() {
public void printMe() {
System.out.println("defined");
}
};
f.printMe();
}
}
From a normal Main, if you called new Bar().printMe it would print "defined" and in the compilation directory you will find Bar1.class
在普通的 Main 中,如果您调用 new Bar().printMe 它将打印“已定义”,并且在编译目录中您将找到 Bar1.class
this section in the above code :
上面代码中的这一部分:
Foo f = new Foo() {
public void printMe() {
System.out.println("defined");
}
};
is called an anonymous inner class.
称为匿名内部类。

