Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java generics - getting the type

Tags:

java

generics

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;
}
like image 571
peter Avatar asked Sep 10 '26 22:09

peter


1 Answers

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
}
like image 147
Michael Borgwardt Avatar answered Sep 13 '26 14:09

Michael Borgwardt



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!