You have 2 solutions :
- If
E
has a no-arg constructor, you can use reflection to build one.
- You can make an abstract method
abstract E buildE();
For the first solution, you will have to pass the class as a parameter of your constructor :
class B<E extends A>{
public B(Class<E> clazz){
//Create instance of E:
E e=clazz.newInstance();
}
}
For the second solution, it means that class B has an abstract method to build the object (it is more or less equivalent to passing a factory):
public class B<E extends A>{
public abstract E buildE();
private void foo(){
E e = buildE();
//Do generic stuff with E
}
}
In this way, if you create a sub class of B, you need to implement this method
public class B1 extends B<Bar>{
//You are required to implement this method as it is abstract.
public Bar buildE(){
..
}
private void anyMethod(){
//call B.foo() which will use B1.buildE() to build a Bar
super.foo();
}
}
IMHO, 2nd solution is far cleaner.