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.

0

3 Answers 3

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.)

Sign up to request clarification or add additional context in comments.

Comments

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.

1 Comment

Can you please elaborate on your second proposed solution?
-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]

4 Comments

-1 This assumes this is an instance of a class extending B and resolving its type parameter with a concrete type, e.g. class C extends B<String>.
@Paul Bellora The questioner asks "in a method of B, I want to get a dummy instance of E", so this is of course a concrete class
Please reread my comment to understand it. Try it with a new B<A> - it will fail on (ParameterizedType)this.getClass().getGenericSuperclass(). Make sure to understand patterns before you use them.
it will fail with new B<String> but not new B<E> where E extends A and A is an abstract class the questioner creates. I'm using this code in production so wanna give an alternative suggestion.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.