Why is anonymous class required in “super type token” pattern in java

江枫思渺然 提交于 2019-12-03 06:50:46

This

ReferenceType<List<Integer>> referenceType = new ReferenceType<List<Integer>>(){

is equivalent to

public class AnonymousReferenceType extends ReferenceType<List<Integer>> {}
...
ReferenceType<List<Integer>> referenceType = new AnonymousReferenceType();

The hack works around Class#getGenericSuperclass() which states

Returns the Type representing the direct superclass of the entity (class, interface, primitive type or void) represented by this Class. If the superclass is a parameterized type, the Type object returned must accurately reflect the actual type parameters used in the source code. The parameterized type representing the superclass is created if it had not been created before. See the declaration of ParameterizedType for the semantics of the creation process for parameterized types. If this Class represents either the Object class, an interface, a primitive type, or void, then null is returned. If this object represents an array class then the Class object representing the Object class is returned.

In other words, the superclass of AnonymousReferenceType is a ParameterizedType representing ReferenceType<List<Integer>>. This ParameterizedType has an actual type argument and that is a List<Integer> which is what appears in the source code.


In your second example, which is not the same as your first,

class ReferenceType<T>{}
class ReferenceTypeSub<T> extends ReferenceType<T>{}

the super class (super type) of ReferenceTypeSub is a ReferenceType<T> which is a ParameterizedType where the actual type argument is a TypeVariable named T, which is what appears in the source code.


To answer your question, you don't need an anonymous class. You just need a sub class which declares the type argument you want to use.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!