类和新实例的 Java 泛型

标签 java generics

在 Java 中,如果我有:

public class Foo<T> {

  public Foo() { }

}

我可以Foo<Integer> foo = new Foo<Integer>();但我找不到使用 class 的等效语法字段,意思是类似 Foo<Integer> foo = Foo<Integer>.class.newInstance();不起作用。有没有办法通过 newInstance 方法使用泛型?

最佳答案

只有在没有参数化类型的情况下才可以做到这一点。 Class.newInstance() 不太值得推荐。你可以这样做:

//Class<Foo<Integer>> clazz = Foo<Integer>.class; <-- Error
Class<Foo> clazz = Foo.class; // <-- Ok
Foo instance = clazz.getConstructor().newInstance();

Why is Class.newInstance() evil?

希望有帮助。

关于类和新实例的 Java 泛型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31287764/

相关文章:

java - 使用Java包命名约定时,如果您不再拥有域名会发生什么

java - MyClass 在两次测试之间保持模拟状态

java - 读取数据库后在 Java 中捕获异常的正确方法

java - 什么是原始类型,为什么我们不应该使用它呢?

swift 泛型 : where in type declaration

c# - 通用函数中的 On<T> 是什么意思

java - WebFlux WebClient中测试状态码时如何获取响应体?

java - 计算文件的总计和平均值

java - 从对象转换为枚举

c# - C# 中是否有 "anonymous"通用标记,如 Java 中的 '?'?