英文:
Question about return type( need to return instances of different classes) in generics
问题
以下是翻译好的部分:
所以我的当前代码看起来是这样的。这个想法是使用通用类型 T 接收不同类的实例,然后返回这些实例。
我应该能够像这样调用类的实例:
```java
new A().add(new B())
public static <T> T add(T t) {
return new T();
}
基本上对我来说,返回类型应该是类本身,这样它可以通过返回类型获取一个新的实例。
有人能指导我逻辑出了什么问题吗?
<details>
<summary>英文:</summary>
So my current code looks like this. The idea is to take in an instance of different classes using generic type T and return those instances.
I should be able to call instances of classes like this
new A().add(new B())
public static <T> T <T> add(T t) {
return new T();
}
Basically to me the return type should be the class itself so that it can take a new instance through the return type.
Can someone guide me as to where my logic is going wrong?
</details>
# 答案1
**得分**: 1
你不能仅通过泛型类型调用构造函数,因为:1. 类型擦除意味着在运行时,`T` 会变成 `Object`(或者是其上界的类型),2. 你不知道构造函数是否一定不带参数。
一个更好的方法是使用 [`Supplier`][1]:
```java
public static <T> T add(Supplier<T> supplier) {
return supplier.get();
}
你可以像这样使用这个方法。使用方法引用,可以非常简洁。
B b = YourClass.add(B::new);
英文:
You can't call a constructor just from the generic type because 1. type erasure means T
gets turned into Object
(or whatever its upper bound is) at runtime, and 2. you don't know that the constructor necessarily takes 0 arguments.
A better way to do it would be with a Supplier
public static <T> T add(Supplier<T> supplier) {
return supplier.get();
}
and you could use this method like this. With method references, it's pretty concise.
B b = YourClass.add(B::new);
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论