Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
636 views
in Technique[技术] by (71.8m points)

java - Why are generics completely disabled when you ignore a parameter type?

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...