2

I have these 2 classes

abstract class A
{
//some abstract methods and variables
}

class B<E extends A>
{
}

Now in a method of B, I want to get a dummy instance of E. How to do that? Is this ok -

E temp = (E)(new Object());

I have control over the class definitions and hence they're flexible.

Sebastian Redl
  • 69,373
  • 8
  • 123
  • 157
ksb
  • 670
  • 8
  • 19

3 Answers3

3

You will need to pass in a factory object (or an instance) into the constructor for B. There is no way of specifying that a generic type parameter has a specific constructor, and the static type is not available at runtime.

(You could fake a distinguished value with E temp = (E)new A() { };, but that is well dodgy. Some of the collection code does something similar only with arrays.)

Tom Hawtin - tackline
  • 145,806
  • 30
  • 211
  • 305
3

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.

Arnaud Denoyelle
  • 29,980
  • 16
  • 92
  • 148
-1

You can use reflection in B to get Class<E>, then get the desired constructor and call newInstance

(Class<E>)((ParameterizedType)this.getClass().getGenericSuperclass()).getActualTypeArguments()[0]
Alan
  • 608
  • 6
  • 14