Re: Annotations and generic programming
On Apr 29, 10:18 pm, kelvSYC <kelv...@gmail.com> wrote:
Now, one of the big criticisms of type-erasure generic programming is
that - well, it's type erasure generic programming: suppose you have
public static <T> List<T> doStuff(){
...
}
Within the body of doStuff(), T.class is an error, and the only way to
get what T stands for is to use that big backhoe that's reflection and
somehow get a Class<T> object - which you would do by passing in a
Class<T>, resulting in...
public static <T> List<T> doStuff(Class<T> tClass) {
...
}
Its not hard to do this anyway.
List<Foo> foos = doStuff(Foo.class);
If you wanted to take T.class, thats as much reflection as Foo.class,
although it does put it in the client code.
Now IMO T.class should really return a Class<T>, just like
Integer.class gives you Class<Integer>, but I guess that other peoples
opinions differed (I am not sure about the argument against it, so
please explain to me what it is).
The argument is that T is not a real type, but a type holder.
Integer.class is a static constant, T.class could not be a constant,
since T could represent Integer or FooBob.
Why do I mention this? It seems like annotations and annotation
processing might be a means to an address this. (If I am wrong about
annotations or annotation processing, please correct me). It seems
like there should be an annotation processor that would take code of
the former form and convert it to code of the latter form (the needed
Class arguments would be the first arguments passed in).
Annotation processors take "@Annotation" annotations, and process
them. There is no @Annotation in your code anywhere...
Again, the type of T us up to the caller of doStuff, so you would have
to know all of the callers before hand. This is not a possible task,
as the calling code could be written and compiled after the fact.
Am I ill-informed on this, and if not, is there such an annotation
processor?
There are annotation processors, and also reflection based frameworks
which use annotations. They however are no use to your problem.
It is considered appropriate to pass Class<T> type into methods as a
type token. It even gives you the ability to call type.cast() if you
need to.