简体   繁体   English

Java是否“缓存”匿名类?

[英]Is Java “caching” anonymous classes?

Consider the following code: 请考虑以下代码:

for(int i = 0;i < 200;i++)
{
  ArrayList<Integer> currentList = new ArrayList<Integer>() {{
    add(i);
  }};
  // do something with currentList
}
  • How will Java treat the class of currentList ? Java如何处理currentList的类?
  • Will it consider it a different class for each of the 200 objects? 对于200个对象中的每一个,它会认为它是一个不同的类吗?
  • Will it be a performance hit even after the first object is created? 即使在创建第一个对象后,它是否会受到性能影响?
  • Is it caching it somehow? 是以某种方式缓存吗?

I'm just curious :) 我只是好奇 :)

ArrayList<Integer> currentList = new ArrayList<Integer>() {{
    add(i);
  }};

is creating a new instance of the anonymous class each time through your loop, it's not redefining or reloading the class every time. 每次通过循环创建匿名类的新实例时,它不是每次都重新定义或重新加载类。 The class is defined once (at compile time), and loaded once (at runtime). 该类定义一次(在编译时),并加载一次(在运行时)。

There is no significant performance hit from using anonymous classes. 使用匿名类没有显着的性能损失。

The compiler is going to transform any anonymous class to a named inner class. 编译器将任何匿名类转换为命名的内部类。 So your code, will be transformed to something along the lines of: 因此,您的代码将转换为以下内容:

class OuterClass$1 extends ArrayList<Integer> {
    OuterClass$1(int i) {
      super();
      add(i);
    }
}

for (int i = 0; i < 200; i++) {
    ArrayList<Integer> currentList = new OuterClass$1(i);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM