In Neal Gafter's "super type token" pattern (http://gafter.blogspot.com/2006/12/super-type-tokens.html), an anonymous object was used to pass in the parameterized type :
class ReferenceType<T>{}
/* anonymous subclass of "ReferenceType" */
ReferenceType<List<Integer>> referenceType = new ReferenceType<List<Integer>>(){
};
Type superClass = b.getClass().getGenericSuperclass();
System.out.println("super type : " + superClass);
Type genericType = ((ParameterizedType)superClass).getActualTypeArguments()[0];
System.out.println("actual parameterized type : " + genericType);
Then result is :
super type : com.superluli.test.ReferenceType<java.util.List<java.lang.Integer>>
actual parameterized type : java.util.List<java.lang.Integer>
My question is, what the magic does the anonymous object "referenceType" do to make it work? If I define a explicit subclass of "ReferenceType" and use it instead of the anonymous style, it doesn't as expected.
class ReferenceType<T>{}
class ReferenceTypeSub<T> extends ReferenceType<T>{}
/* explicitly(or, named) defined subclass of "ReferenceType" */
ReferenceType<List<Integer>> b = new ReferenceTypeSub<List<Integer>>();
Type superClass = b.getClass().getGenericSuperclass();
System.out.println("super type : " + superClass);
Type genericType = ((ParameterizedType)superClass).getActualTypeArguments()[0];
System.out.println("actual parameterized type : " + genericType);
The result is :
super type : com.superluli.test.ReferenceType<T>
actual parameterized type : T
This
is equivalent to
The hack works around
Class#getGenericSuperclass()
which statesIn other words, the superclass of
AnonymousReferenceType
is aParameterizedType
representingReferenceType<List<Integer>>
. ThisParameterizedType
has an actual type argument and that is aList<Integer>
which is what appears in the source code.In your second example, which is not the same as your first,
the super class (super type) of
ReferenceTypeSub
is aReferenceType<T>
which is aParameterizedType
where the actual type argument is aTypeVariable
namedT
, 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.