gpt4 book ai didi

c# - 在 Java 中创建 T 的新实例

转载 作者:行者123 更新时间:2023-11-30 19:48:15 25 4
gpt4 key购买 nike

在 C# 中,我们可以定义一个泛型 class A<T> where T : new() .在这段代码中,我们可以创建一个 T 的实例。与 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();
}
}

如何让这个方法更优雅?

最佳答案

不,你不能做新的 T(),因为你不知道 T 是否有一个无参数的构造函数,并且因为 type erasure 导致 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);
}

关于c# - 在 Java 中创建 T 的新实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5710546/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com