How*_*ard 2 c# java generics design-patterns
在C#中,我们可以定义一个泛型class A<T> where T : new().在这段代码中,我们可以创建一个Twith 的实例new T().这是如何在Java中实现的?我读了一些文章说这是不可能的.
我使用的原因是在C#中使用泛型的单例模式:
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();
}
}
Run Code Online (Sandbox Code Playgroud)
并且方法使这种方法更优雅?
不,你不能做新的T(),因为你不知道T是否有一个没有arg构造函数,并且因为类型擦除而在运行时不存在T的类型.
要创建T的实例,您需要有类似的代码,
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);
}
Run Code Online (Sandbox Code Playgroud)