关于范型中返回类型的问题(需要返回不同类的实例)。

huangapple go评论105阅读模式
英文:

Question about return type( need to return instances of different classes) in generics

问题

以下是翻译好的部分:

  1. 所以我的当前代码看起来是这样的。这个想法是使用通用类型 T 接收不同类的实例,然后返回这些实例。
  2. 我应该能够像这样调用类的实例:
  3. ```java
  4. new A().add(new B())
  1. public static <T> T add(T t) {
  2. return new T();
  3. }

基本上对我来说,返回类型应该是类本身,这样它可以通过返回类型获取一个新的实例。

有人能指导我逻辑出了什么问题吗?

  1. <details>
  2. <summary>英文:</summary>
  3. 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.
  4. I should be able to call instances of classes like this

new A().add(new B())

  1. public static &lt;T&gt; T &lt;T&gt; add(T t) {
  2. return new T();
  3. }
  1. Basically to me the return type should be the class itself so that it can take a new instance through the return type.
  2. Can someone guide me as to where my logic is going wrong?
  3. </details>
  4. # 答案1
  5. **得分**: 1
  6. 你不能仅通过泛型类型调用构造函数,因为:1. 类型擦除意味着在运行时,`T` 会变成 `Object`(或者是其上界的类型),2. 你不知道构造函数是否一定不带参数。
  7. 一个更好的方法是使用 [`Supplier`][1]:
  8. ```java
  9. public static <T> T add(Supplier<T> supplier) {
  10. return supplier.get();
  11. }

你可以像这样使用这个方法。使用方法引用,可以非常简洁。

  1. 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

  1. public static &lt;T&gt; T add(Supplier&lt;T&gt; supplier) {
  2. return supplier.get();
  3. }

and you could use this method like this. With method references, it's pretty concise.

  1. B b = YourClass.add(B::new);

huangapple
  • 本文由 发表于 2020年5月29日 09:53:06
  • 转载请务必保留本文链接:https://go.coder-hub.com/62077414.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定