0

Can we instantiate an object from generic type at runtime? I've a class:

MyClass<T> implements SomeInterface<T> {
..
public T someMethod() {
return <object of Type T> // Desired!!!
}
..
}

Or let suppose I'm calling this method from some other class where I need an instance of generic type:

TestMayClass {
DesiredClass t = new MyClass<DesiredClass>().someMethod();
// Can I have generics type at run time and construct object from it then return to calling method? Manipulating generic type??
}

: This code's not compiled, it's just imaginary code to have something is similar way.

Arun
  • 2,360
  • 2
  • 17
  • 23
  • Generics in Java are erased at runtime. The only way to achieve something like that is to pass a proper `Class` object and use `newInstance` or one of its constructors if you know which arguments they need. – RealSkeptic Aug 13 '15 at 10:10
  • Yeah correct! erasure are there but a Class object still maintains some information about generics. Its not completely erased. thanks – Arun Aug 13 '15 at 10:28

1 Answers1

2

No you can't do that in Java. Even if we put type erasure aside, how could the compiler know that the invoked constructor exists?

The closest thing in Java that could suit your requirement is reflection.

Dragan Bozanovic
  • 23,102
  • 5
  • 43
  • 110
  • Its just a case, I can play around reflection to instantiate an object if I have class anyhow at run-time with me. So Think this problem is as I want to have a class of Type given at the time of declaration/initialization. Yeah erasure are there but a Class object maintains some information about generics, I'm not sure if it have the exact type we are declaring an reference/object. So wtill I've same doubt about to have type? Thanks – Arun Aug 13 '15 at 10:27