How to get a static reference to a genericized class?  
Author Message
Nate





PostPosted: 2005-2-3 6:25:00 Top

java-programmer, How to get a static reference to a genericized class? I can explain much more concisely with an example...

class Cow<C> {
public Cow (Class<C> clazz) {}
}

class Milk<T> {}

class Moo {}

Now let's say I want to create a Cow< Milk<Moo> >. What do I pass to
the Cow constructor?

new Cow<Milk<Moo>>(Milk.class);

This results in the error "The constructor Cow<Milk<Moo>>(Class<Milk>)
is undefined". This is because the constructor is actually
"Cow<Milk<Moo>>(Class<Milk<Moo>>)". How can I get a reference to
Class<Milk<Moo>> without having an instance of a Milk<Moo>?

new Cow<Milk<Moo>>((Class<Milk<Moo>>)Milk.class);

This is better but results in the warning "Type safety: The cast from
Class<Milk> to Class<Milk<Moo>> will not check conformance of type
arguments at runtime". Damnit compiler, I know better than you! ;)
Is there a better solution?

 
Nate





PostPosted: 2005-2-8 4:58:00 Top

java-programmer >> How to get a static reference to a genericized class? No simple solution I guess.