0

I don't know exactly how to define my doubt so please be patient if the question has already been asked.

Let's say I have to dynamically instantiate an object. This object will surely be instance of a subclass of a known, immutable class A. I can dynamically obtain the specific implementation class.

Would it be better to use reflection exactly as if I didn't know anything about the target class, or would it be preferrable/possible to do something like:

A obj = (Class.forName("com.package.Sub-A")) new A();

where Sub-A extends A ? The purpose would be to avoid reflection overhead times...

Esailija
  • 138,174
  • 23
  • 272
  • 326
Ema
  • 104
  • 11
  • This code doesn't compile. It doesn't even make sense. The result of `new A()` is an A, not the class of A, or the class of any of its subclasses. Please refine your question. – user207421 Jul 11 '12 at 10:48

1 Answers1

1

Usually this is done via

Class.forName("com.package.Sub-A").getConstructor(param types).newInstance(param values)

And to avoid reflection overherad, you just cache constructor object.

Yuriy Nakonechnyy
  • 3,742
  • 4
  • 29
  • 41
Konstantin Pribluda
  • 12,329
  • 1
  • 30
  • 35
  • Thank you, and what do you mean with "cache constructor object"? – Ema Jul 11 '12 at 09:18
  • getConstructor(...) delivers to you object of type (Surprise!!!!) java.lang.reflect.Constructor - and this object can be used to create multiple instaces of this class. – Konstantin Pribluda Jul 11 '12 at 10:51