Instantly generate type in java

I am stuck. Coming from C ++, I thought this would just work, but it is not. Could you give me some advice? I will try not to end up creating a create method in every class used for T.

public class A<T>{ private T t_; public A(){ t_ = new T(); //error } } 

Also, I don't want to have a constructor similar to: A (Class classT) {... Ideally, I would like to have something like this C ++ code.

 template<class T> class A{ private: T t_; public: A(){} }; 

Thanks for the help.

+8
java object generics instantiation templates
source share
4 answers

You cannot do such things in Java. More on erasing styles: http://docs.oracle.com/javase/tutorial/java/generics/erasure.html

+7
source share

Besides the type-erasing problem that makes this impossible anyway, you simply cannot guarantee that T has an open constructor without arguments!

The traditional workaround is to pass factory objects that provide methods that you can use to get T objects. A simple example would be

 interface Factory<T> { T create(); } 

and then your class can get Factory<T> and call create() on it to get more T s. More complex examples may require additional arguments for the create method, for example, or overloading.

Less - pretty workarounds include explicit reflection passing around Class<T> objects. For example, ArrayList.class.newInstance() returns a newly constructed raw ArrayList . You must explicitly pass the Class object, and the reflection-based approach is slower than a regular constructor or factory object (although the speed of reflection has been improving lately). You also depend on a class demonstrating the no-arg constructor, which is not always the case. It can be made to work, but it is never what I would call "enjoyable."

(However, there are links to the fact that the situation may change somewhat in Java 8 using the Lambda project and friends.)

+11
source share

Sorry you were not able to remove you, but this is simply not possible in java without constructors.

Java discards general information at runtime (see type erasure)

+5
source share

try the following:

 private <E extends ISomething> E createInstance(Class<E> clazz) { E ret; try { ret = clazz.newInstance(); ret.setSomething(something); } catch (InstantiationException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } return ret; } 
0
source share

All Articles