How does the JLS specify that wildcards cannot be formally used within methods?

前端 未结 3 2003
Happy的楠姐
Happy的楠姐 2020-12-11 08:40

I\'ve always been wondering about some weird aspect of Java generics and the use of wildcards. Let\'s say, I have the following API:

public interface X

        
3条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-11 08:53

    Not having been involved in writing the JLS, my best guess is simplicity. Imagine silly, yet (syntactically) valid expressions such as (x = new X()).set(x.get());. Tracking captures of wildcards can get tricky.

    I think of capturing wildcards not as boilerplate, but as having done something right. It's a sign that your API is free of type parameters which client code does not need.

    Edit: The current behavior is specified in JLS §4.5.2. The x gets capture-converted for each member access -- once for x.set(...) and once for x.get(). The captures are distinct and thus not known to represent the same type.

提交回复
热议问题