为什么在编译时创建两个类文件? [英] Why are two class files created on compiling?

查看:59
本文介绍了为什么在编译时创建两个类文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道,当一个类具有内部类时,该类将被编译为两个类文件.今天我的代码如下

I knew that when a class has an inner class then this class will be compiled to two class files. Today I have codes as below

public class GenericDeserializer {

    public static void main(String[] args) {
        String cityPageLoadJson = "{\"count\":2,\"pageLoad\":[{\"id\":4,\"name\":\"HAN\"},{\"id\":8,\"name\":\"SGN\"}]}";
        Type type = new TypeToken<GenericResult<City>>() {
        }.getType();
        Gson gson = new GsonBuilder().setPrettyPrinting().create();
        GenericResult<City> cityPageLoad = gson.fromJson(cityPageLoadJson, type);
        for (City city : cityPageLoad.getPageLoad()) {
            System.out.println(gson.toJson(city));
        }
    }

}

尽管上面的一个没有内部类,但是java编译器仍然创建了两个类文件:

Although the above one has no inner class, java compiler still creates two class files:

GenericDeserializer.class
GenericDeserializer$1.class

使用 Java Decompiler 工具,我看到了第二个的内容

Using Java Decompiler tool, I see content of the second

package net.tuandn.training.lesson.gson;

import com.google.gson.reflect.TypeToken;
import net.tuandn.training.model.City;
import net.tuandn.training.model.GenericResult;

final class GenericDeserializer$1 extends TypeToken<GenericResult<City>>
{
}

有人可以解释为什么要创建此类吗?
以及何时在编译时创建多个类文件?

Could anybody please explain why this class is created?
And when are multiple class files created on compiling?

非常感谢!

推荐答案

new TypeToken<GenericResult<City>>() {
}

创建一个匿名内部类.就像内部类一样,匿名内部类也被编译为单独的类文件.由于匿名类没有名称,这就是为什么 numbers 用于为每个此类生成唯一名称的原因.您在 $ 之后看到的数字是该匿名类的编号,因为它们在您的封闭类中按顺序排列.

creates an anonymous inner class. Anonymous inner classes, just like inner classes are compiled to separate class files. Since anonymous class don't have name, that is why numbers are used to generate unique names for each such classes. The number you see there after $ is the numbering for that anonymous class, as they come in order in your enclosing class.

如果您使用更多类似的匿名类,则数字将增加 1 .因此,对于更多匿名类,生成的类文件将如下所示:

If you use more anonymous classes like that, the number will increment by 1. So for more anonymous classes, the generated class files would look like:

GenericDeserializer$1.class
GenericDeserializer$2.class
GenericDeserializer$3.class
GenericDeserializer$4.class
....

对于内部类,正如您已经注意到的那样, $ 之后的值是内部类的名称.

For inner classes however, the value after the $ is the name of the inner class, as you already would have noticed.

什么时候编译时会创建多个类文件?

And when are multiple class files created on compiling?

是的,这些类是在编译顶级类时生成的.

Yes, those classes are generated, when you compile your top-level class.

这篇关于为什么在编译时创建两个类文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆