Create a new instance of T in Java

in C #, we can define a generic class A<T> where T : new() . In this code, we can create an instance of T with new T() . How is this implemented in Java? I read an article that says this is not possible.

The reason I used has a singleton patten using common code in C #, for example:

 public static class Singleton<T> where T : new() { private static T instance; public static T Instance { get { if (instance == null) { instance = SingletonCreater.Instance; } return instance; } } static class SingletonCreater { internal static readonly T Instance = new T(); } } 

And how to make this method more graceful?

+2
source share
3 answers

No, you cannot make a new T (), because you do not know if T has an arg constructor without an argument, and because the type T is absent at runtime due to the erasure of styles .

To create an instance of T, you need to have code like

 public <T> T create(Class<T> clazz) { try { //T must have a no arg constructor for this to work return clazz.newInstance(); } catch (InstantiationException e) { throw new IllegalStateException(e); } catch (IllegalAccessException e) { throw new IllegalStateException(e); } 
+7
source

Yes, new T() not possible, since generic is a compile-time function in Java. At run time, generic information is lost; therefore, you cannot make new T() , since the JVM has no idea what T at runtime.

You may not be lucky to use the exact syntax you talked about using Java.

+1
source

Thanks guys, we cannot use it in JAVA. As a Sbridges method, in C # we can implement the following:

 static T Create(Type type) { return (T)Activator.CreateInstance(type); } 

or even simpler:

 static T Create() { return Activator.CreateInstance<T>(); } 

Just let me know.

0
source

All Articles