Constructing a Java generic with an unknown subtype-Collection of common programming errors
The code that interacts with the Blah makes use of the T class to do some reflection. It needs a concrete T instead of some parent class. – evilfred
No, the code can’t interact with T at runtime, because it never gets to know what T is. Generics are ONLY relevant at compile time. What happens is that generics are preprocessed BEFORE the Java code is compiled into byte code. Byte code knows nothing about generics, ever.
In:
protected void addThing(T obj) {
process(new Blah(obj));
}
Blah[Animal] is fixed at compile-time and you cannot turn the process method’s signature into Blah[Giraffe]. Not an option.
What the code deals with at runtime is Blah[Animal], not T (or Blah< T >). Ever. What ever the subtype of what you create with new Blah< T > is, byte code will consider it as Blah[Animal]. You can’t create new types at runtime.
Your idea of a solution:
Blah(Object obj) {
// Undesirable downcast.
this.thing = (T)obj;
}
is not going to work, because T will be resolved at compile time.
Now if you want to create Blah[Giraffe], don’t delegate the creation of new Blah to the addThing method. Do something like this:
private class Blah { }
private class Giraffe { }
public Test_1() {
Blah f = new Blah();
addThing2(f);
}
public void addThing2(Blah obj) {
process(obj);
}
public void process(Blah obj) { }
If you can’t modify addThing, then you probably don’t need to worry about creating a generic with an unknown subtype at runtime in the first place (because is it is impossible in Java). Your issue is/would actually be a non-problem (for the process method at least).