Java隐藏特性

双花括号初始化语法(DoubleBraceInitialization)

1
2
3
4
5
6
7
8
9
// 这里解释下这两个括号:
// 第一个括号创建了一个新的匿名内部类,相信这个大家都知道;
// 第二个括号声明了匿名内部类实例化时运行的实例初始化块。
removeProductsWithCodeIn(new HashSet<String>() {{
add("XZ13s");
add("AB21/X");
add("YYLEX");
add("AR5E");
}});

注意:此特性可能存在的问题;

  1. gson 不能正确解析双花括号语法(【Java】那些踩过的坑 | 比特楼)
  2. 永远不要使用双花括号初始化实例,否则就会 OOM! - SegmentFault 思否
    (匿名内部类,可能会导致 OOM)
  3. Caused by: com.esotericsoftware.kryo.KryoException: Class cannot be created (missing no-arg constructor): com.lyloou.jetcache.UserServiceImpl$1
    This is an anonymous class, which is not serializable by default in Kryo. Possible solutions: 1. Remove uses of anonymous classes, including double brace initialization, from the containing class. This is the safest solution, as anonymous classes don’t have predictable names for serialization.