You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

为何C::size方法引用非法?关于JLS相关规则的疑问

关于方法引用歧义性的疑问

我对方法引用(method reference)的工作原理存在一些困惑,下面是来自JLS 15.13.1的歧义示例:

歧义示例:

interface Fun<T,R> { R apply(T arg); } 

class C { 
    int size() { return 0; } 
    static int size(Object arg) { return 0; } 
    void test() { 
        Fun<C, Integer> f1 = C::size; 
        // Error: instance method size() 
        // or static method size(Object)? 
    } 
}

我尝试分析这段代码,明确该方法引用指向的方法调用,根据JLS 15.13.1的相关规则:

• 第一步:确定搜索类型:
– 若方法引用表达式为ReferenceType ::[TypeArguments] Identifier形式,搜索类型是对ReferenceType应用capture conversion(§5.1.10)后的结果。

因此搜索类型为类类型C。

• 第二步:针对参数数量为n的目标函数类型,识别potentially applicable方法集合:
– 若方法引用表达式为ReferenceType :: [TypeArguments] Identifier形式,potentially applicable方法包括:
› 搜索类型的成员方法中,对于名称为Identifier、arity为n、类型参数为TypeArguments且出现在与方法引用表达式同一类中的方法调用而言,属于potentially applicable(§15.12.2.1)的方法;加上
› 搜索类型的成员方法中,对于名称为Identifier、arity为n-1、类型参数为TypeArguments且出现在与方法引用表达式同一类中的方法调用而言,属于potentially applicable的方法。

按照这个规则,int size()和int size(Object arg)都属于potentially applicable方法。不过potentially applicable规则还要求参数与参数值具备potentially compatible特性,这里是否因为没有提及调用的参数类型,所以不需要考虑这一点?

内容的提问来源于stack exchange,提问作者user24723440

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.16 21:35:08