通用擦除概念 [英] Generic Erasure concept

查看:81
本文介绍了通用擦除概念的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请你帮我理解这里的通用概念。

Could you please help me to understand the generic concept here.

// Can't create an instance of T.
class Gen<T> {
  T ob;

  Gen() {
    ob = new T(); // Illegal!!!
  }

  public static void main() {

    Gen<Integer> genobj = new Gen<Integer>(); //Error
  }
}

编译Java代码时,所有通用类型
信息被删除(删除)。这意味着用它们的绑定
类型替换类型参数,如果没有指定显式绑定,则为Object,然后应用适当的
强制转换(由类型参数确定)以保持类型与类型$的兼容性b $ b由类型参数指定。编译器还强制实现这种类型的兼容性。

When your Java code is compiled, all generic type information is removed (erased). This means replacing type parameters with their bound type, which is Object if no explicit bound is specified, and then applying the appropriate casts (as determined by the type arguments) to maintain type compatibility with the types specified by the type arguments. The compiler also enforces this type compatibility.

我的问题: - 为什么java编译器在这里抛出错误?
赞美之后。

My question:-Why java complier is throwing error here ? Bevause after complitaion .

谢谢

推荐答案

那里有几种方法可以解决这个问题:

There are a few ways that may work out here:

来自逻辑POV:

它甚至不能保证任何模板参数<$ c $你使用c> T 有一个默认构造函数。这显然提供了如何处理缺省构造函数缺失的问题。可能的解决方案是产生运行时错误,编译时错误或禁止任何不提供默认构造函数的 T 。后者显然会破坏模板定义,允许任何 T 。并且运行时错误会使事情变得复杂并且产生与上面提到的相同的问题。仍然是首先阻止此行为并抛出编译时错误。

From a logical POV:
It's not even guaranteed that whatever template-parameter T you use has a default-constructor. Which obviously offers the problem of how to handle the absence of a default-constructor. Possible solutions would be to produce a runtime-error, compile-time error or disallow any T that doesn't provide a default-constructor. The latter would obviously break the template-definition, which allows any T. And the runtime-error would complicate things quite a bit and yield the same problem as mentioned above. Remains preventing this behavior in the first place and throwing a compile-time error.

从内部视图:

假设我们可以使用提供的码。那它将如何运作?由于擦除,新的T()将产生对象。但是如果 T 整数呢?好吧,我们搞砸了。 对象不是 Integer ,因此我们将得到一个普通的类转换异常。

From a internal view:
Let's assume we could use the provided code. Then how would it work? Due to erasure, new T() would produce an Object. But what if T is Integer? Well, we're screwed. An Object is not an Integer, so we'll get a plain class-cast exception.

总结一下:允许上面的编译不适用于实际的POV,另外打破了java中当前泛型的定义。

So in summary: allowing the above to compile wouldn't work from a practical POV and in addition break the current definition of generics in java.

这篇关于通用擦除概念的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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