为什么忽略参数类型时泛型完全被禁用? [英] Why are generics completely disabled when you ignore a parameter type?

查看:90
本文介绍了为什么忽略参数类型时泛型完全被禁用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

作为这个问题,首先是背景



给定一个类声明:

  public class SomeClass< T> 

以及不使用泛型参数的子类:

  public class SomeSubClass extends SomeClass 

在SomeClass声明如下:

 受保护的Map< String,Object> getMap(Object param){
}

如果子类调用方法如下: / p>

 地图< String,Object> val = getMap(param); 

编译器在本质上抱怨getMap返回一个普通的Map,并且对通用化的Map有一个未检查的赋值。为什么会这样?这是对泛型的文档化的期望,是有原因的吗?

解决方案

我不太清楚理由这个,但是这种行为在 Java语言规范JLS S4.8


原始类型的超类(分别为超接口)是超类的超类接口)的任何参数化调用。

鉴于在新代码中非常不鼓励使用Raw类型,他们只需要简单的规则用于原始和参数化类型之间的交互,我猜。


As a followup to this question, first the background

Given a class with this declaration:

public class SomeClass<T>

And a subclass that does not use the generic parameter:

public class SomeSubClass extends SomeClass

A method on SomeClass declared as follows:

protected Map<String, Object> getMap(Object param) {
}

If the subclass calls the method like this:

Map<String, Object> val = getMap(param);

The compiler complains in essence that getMap returns a plain Map and there is an unchecked assignment to a genericized Map. Why is this the case? Is this a documented expectations with Generics, and is there a reason for it?

解决方案

I don't quite know the rationale for this, but this behavior is specified in the Java Language Specification JLS S4.8:

The superclasses (respectively, superinterfaces) of a raw type are the erasures of the superclasses (superinterfaces) of any of its parameterized invocations.

Given that it's highly discouraged to use Raw types in new code, they wanted to simply the rules for interaction between Raw and Parameterized types I guess.

这篇关于为什么忽略参数类型时泛型完全被禁用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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