我可以将泛型属性存储到对象的字段中 [英] Can I store the generics attribute into an object's field

查看:160
本文介绍了我可以将泛型属性存储到对象的字段中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设以下类存根:

  public class Foo< T> {
私人课程< T>类型;

public Foo< T> (){}
}

我可以存储泛型类型 T 在构造函数中的类型字段中,而不改变构造函数的签名为 public Foo< T>(Class< T>类型)

如果是,如何?如果不是,为什么?



type = T 似乎不起作用。

$无类型擦除意味着您必须在执行时提供 您可以提供 T Class 的实例,但类本身只会出现T替换为 Object



这种事情是Java泛型与.NET中最大的缺点之一。 (另一方面,差异的故事更强 - 如果更容易混淆 - 在Java中比在.NET中)。

Assuming the following class stub:

public class Foo<T> {
  private Class<T> type;

  public Foo<T> () {}
}

Can I store the generic type T into the field type in the constructor, without changing the constructor's signature to "public Foo<T> (Class<T> type)"?

If yes, how? If no, why?

"type = T" doesn't seem to work.

解决方案

No - type erasure means that you have to provide something at execution time. You could provide either an instance of T or Class<T> but the class itself will just have every occurrence of T replaced with Object.

This kind of thing is one of the biggest disadvantages of Java's generics vs those in .NET. (On the other hand, the variance story is stronger - if more confusing - in Java than in .NET.)

这篇关于我可以将泛型属性存储到对象的字段中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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