Issues relating to type parameters in Java method calls

前端 未结 1 639
隐瞒了意图╮
隐瞒了意图╮ 2020-12-18 23:28

The Java Language Specification for Java 8 provides an example of a method call with a type argument in \"Example 4.11-1. Usage of a Type\":

 void l         


        
相关标签:
1条回答
  • 2020-12-19 00:01

    Following are the ways of method invocation :

    JLS 15.12 lists following ways for invocation of method,

    • MethodName ( [ArgumentList] ) (Note : This does not have type argument)
    • TypeName.[TypeArguments] Identifier ( [ArgumentList] )
    • ExpressionName.[TypeArguments] Identifier ( [ArgumentList] )
    • Primary.[TypeArguments] Identifier ( [ArgumentList] )
    • super.[TypeArguments] Identifier ( [ArgumentList] )
    • TypeName.super.[TypeArguments] Identifier ( [ArgumentList] )

    So, it is there in Java language specification that method with expression or type name can have type arguments but note that in first method call you can not specify type argument as it's illegal.

    Note that only this does not have allowed this but static call and super method calls can also have type arguments and those are totally legal.

    static void m() { }
    
    void test() {
       ClassName.<Integer>m();//Also compiles
    }
    

    Other than that you will have following warning,

    Unused type arguments for the non generic method m() ...

    Which stands for following statement of JLS 15.12.2.1,

    This clause implies that a non-generic method may be potentially applicable to an invocation that supplies explicit type arguments. Indeed, it may turn out to be applicable. In such a case, the type arguments will simply be ignored.

    It says Indeed, it may turn out to be applicable (at run time)

    Moreover,

    This rule stems from issues of compatibility and principles of substitutability. Since interfaces or superclasses may be generified independently of their subtypes, we may override a generic method with a non-generic one. However, the overriding (non-generic) method must be applicable to calls to the generic method, including calls that explicitly pass type arguments. Otherwise the subtype would not be substitutable for its generified supertype.

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