V
verec
import java.util.List;
public class GenericGotchas {
void foo(Class c) {
System.out.println(c.getSimpleName()) ;
}
void doesCompile() {
foo(List.class) ;
}
void doesNotCompile() {
foo(List<String>.class) ; // compile error (1)
}
static class Test<E> {
Test(E e) { }
static <E> Test<E> // fine (2)
newTest(E e) {
return new Test<E>(e) ;
}
static <E> Test<E> // compile error (3)
singletonDoesNotCompile ;
}
}
Case 1 is extremely unfortunate. I want to maintain
a map of (some) classes/interfaces to (some of) their
instances. This works UNLESS any of the class is a
parameterized one, in which case I couldn'y find a
way to name it.
For case 2, even though you can create "static generic"
factories (2), you CANNOT cache (3) the to be returned result.
I'm certain the powers that be have tons of explanations
involving type erasure, "reification" and many other
beasts, but the end result is that, in practice, this sucks!
This far, short of dropping the generic stuff altogether,
I haven't found any workaround for either of those two cases.
Any idea?
Many thanks
public class GenericGotchas {
void foo(Class c) {
System.out.println(c.getSimpleName()) ;
}
void doesCompile() {
foo(List.class) ;
}
void doesNotCompile() {
foo(List<String>.class) ; // compile error (1)
}
static class Test<E> {
Test(E e) { }
static <E> Test<E> // fine (2)
newTest(E e) {
return new Test<E>(e) ;
}
static <E> Test<E> // compile error (3)
singletonDoesNotCompile ;
}
}
Case 1 is extremely unfortunate. I want to maintain
a map of (some) classes/interfaces to (some of) their
instances. This works UNLESS any of the class is a
parameterized one, in which case I couldn'y find a
way to name it.
For case 2, even though you can create "static generic"
factories (2), you CANNOT cache (3) the to be returned result.
I'm certain the powers that be have tons of explanations
involving type erasure, "reification" and many other
beasts, but the end result is that, in practice, this sucks!
This far, short of dropping the generic stuff altogether,
I haven't found any workaround for either of those two cases.
Any idea?
Many thanks