在Java中创建的T新实例 [英] Create new instance of T in Java

查看:857
本文介绍了在Java中创建的T新实例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在C#中,我们可以定义一个通用类A< T>其中T:new()。在这段代码中,我们可以用 new T()创建一个 T 的实例。这在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 does this implement in Java? I read some article which says it's impossible.

我使用的原因是在C#中使用泛型使用单例模式:

The reason that I used have a singleton patten using generic in C# like:

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();
    }
}

还有更好的方法吗? p>

And way to make this method more graceful?

推荐答案

没有你不能做新的T(),因为你不知道T是否有一个没有arg构造函数,由于类型删除,T的类型在运行时不存在。

No you can't do new T(), since you don't know if T has a no arg constructor, and because the type of T is not present at runtime due to type erasure.

要创建T的实例,您需要具有

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);
}

这篇关于在Java中创建的T新实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆