Forward Reference of Type Parameter in Java Generics

后端 未结 2 1934
灰色年华
灰色年华 2021-02-09 22:46

According to Java Generics FAQ http://www.angelikalanger.com/GenericsFAQ/FAQSections/TypeParameters.html#FAQ302 a type parameter cannot be forward-referenced in this way

<
相关标签:
2条回答
  • 2021-02-09 23:25

    I'm not sure this is true. I looked over the Java Language Specification and in §6.3 there's this discussion of the scopes of type parameters:

    The scope of an interface's type parameter is the entire declaration of the interface including the type parameter section itself. Therefore, type parameters can appear as parts of their own bounds, or as bounds of other type parameters declared in the same section.

    The scope of a method's type parameter is the entire declaration of the method, including the type parameter section itself. Therefore, type parameters can appear as parts of their own bounds, or as bounds of other type parameters declared in the same section.

    The scope of a constructor's type parameter is the entire declaration of the constructor, including the type parameter section itself. Therefore, type parameters can appear as parts of their own bounds, or as bounds of other type parameters declared in the same section.

    (My emphasis).

    This suggests that in the declaration

    that B is indeed in scope when writing A extends B.

    Furthermore, §4.4 of the JLS says, when referring to the bound on a type variable, that

    The bound consists of either a type variable, or a class or interface type T

    Which suggests that not only is B in scope in <A extends B, B>, but that it's a perfectly legal bound on A.

    Finally, to top things off, this code compiles in javac:

    public class Test {
         public static <A extends B, B> A test(B obj) {
             return null;
         }
    }
    

    So I'm pretty sure that this is perfectly legal Java code and that the example you've linked to is either wrong or is referring to something else.

    Hope this helps, and let me know if there's a flaw in my reasoning!

    0 讨论(0)
  • 2021-02-09 23:27

    It is completely legal, say more, you can imagine that A extends C which is generally extends B. So what would you say about when C extends B?

    0 讨论(0)
提交回复
热议问题