问题描述
Java中的Double Brace初始化语法( {{...}}
)是什么?
What is Double Brace initialization syntax ({{ ... }}
) in Java?
推荐答案
双括号初始化创建一个从指定类派生的匿名类(外部大括号),并在该类中提供初始化块( inner 大括号)。例如。
Double brace initialisation creates an anonymous class derived from the specified class (the outer braces), and provides an initialiser block within that class (the inner braces). e.g.
new ArrayList<Integer>() {{
add(1);
add(2);
}};
请注意,使用此双括号初始化的效果是您正在创建匿名内部类。创建的类有一个隐含的这个
指向周围外层类的指针。虽然通常不是问题,但在某些情况下会导致悲伤,例如:在序列化或垃圾收集时,值得了解这一点。
Note that an effect of using this double brace initialisation is that you're creating anonymous inner classes. The created class has an implicit this
pointer to the surrounding outer class. Whilst not normally a problem, it can cause grief in some circumstances e.g. when serialising or garbage collecting, and it's worth being aware of this.
这篇关于什么是Java中的Double Brace初始化?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!