昨天在使用fastjon时,很习惯的用了JSONObject
的
<T> T parseObject(String text, TypeReference<T> type, Feature... features) { ...}
这个方法来解析带有多级泛型的json数据。 写完后突发奇想,为什么其中的type 不是 new TypeReference<List<Search>>()
而是new TypeReference<List<Search>>(){}
。 既不像一般的匿名内部类需要实现方法,又不像一般的创建一个匿名类不加{}。
google了下,在stackoverflow上,有人问了同样的问题
https://stackoverflow.com/questions/3688503/new-object-construct
下面高票的解答是
This construct makes actually two things: 1) It declares an anonymous
class which extends the class you use in the constructor and 2)
creates an instance of this anonymous class. Edit: When using such a
construct you can observe the anonymous class by looking at the
generated .class files. There is the normal MyClass.class file and
another one for each anonymous subclass: MyClass$1.class for the first
and so on.
翻译过来是
这个构造函数做了两件事: 1)声明了一个匿名类,这个匿名类继承了构造函数使用的这个类 ,2)创建了一个匿名类实例。
可以通过生成的class文件观察匿名类, 如果有一个普通的MyClass.class文件,每个匿名子类有一个:MyClass $1.class 等等
看完之后知道是允许这种写法,感觉还是没法解释fastjson 的TypeReference 为什么要这样写。
后面在知乎上看到一个答案,解了心中的惑 https://www.zhihu.com/question/49330534
是因为TypeReference 的构造函数是protected 的
当你想使用一个类的protected 方法时,但是又不和这个类在同一个包下,你是没办法调用的。这时候匿名类就派上用场了,你可以声明一个匿名类继承该类,并定义一个方法,在这个方法内使用super调用你想调用的那个方法(其实你也可以写个类继承这个类,就能调用父类的protected方法了,但是匿名类更简洁,因为你只想调用这个方法而已)