Duplicate: Instantiating generics type in java
Hi! I'm a c# guy giving Java a try .. so how would I do the following in java.
in C#
public T create_an_instance_of<T>(){
T instance = default (T);
// here's usually some factory to create the implementation
instance = some_factory.build<T>();
// or even..
instance = some_factory.build(typeOf(T) );
return instance;
}
Java's generics are based on type erasure. That allows them to be downwards-compatible, but means that you cannot use the type parameter itself, because it does not exist at runtime.
The closest thing you can do is this:
public <T> T create_an_instance_of(Class<T> c){
return c.newInstance(); // or use constructors via reflection
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With