有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java当这样的方法存在时,为什么会抛出'NoSuchMethodException'?

我需要这段代码(在对细化类型使用模式匹配后调用匿名类的方法)

(new {
    def foo : Unit = println("Called foo method")
} : Any) match {
    case f : {def foo : Unit} ⇒
        println("Has foo method")
        f.foo
}

印刷

Has foo method
Called foo method

(以及未经检查的警告)

我知道由于类型擦除,匹配总是成功的,但这不应该导致问题,因为f的运行时类型(甚至考虑擦除)应该是$anon$NameOfSomeAnonymousClassThatHasAfooMethod

当进入Scala REPL(2.9.1)时,它实际上抛出^{

<console>:11: warning: refinement AnyRef{def foo: Unit} in type pattern AnyRef{def foo: Unit} is unchecked since it is eliminated by erasure
              case f : {def foo : Unit} ⇒
                       ^
Has foo method
java.lang.NoSuchMethodException: $anon$1.foo()
        at java.lang.Class.getMethod(Class.java:1622)
        at .reflMethod$Method1(<console>:13)
        at .<init>(<console>:13)
        at .<clinit>(<console>:13)
        at .<init>(<console>:11)
        at .<clinit>(<console>)
        at $print(<console>)
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
        at java.lang.reflect.Method.invoke(Method.java:616)
        at scala.tools.nsc.interpreter.IMain$ReadEvalPrint.call(IMain.scala:704)
        at scala.tools.nsc.interpreter.IMain$Request$$anonfun$14.apply(IMain.scala:920)
        at scala.tools.nsc.interpreter.Line$$anonfun$1.apply$mcV$sp(Line.scala:43)
        at scala.tools.nsc.io.package$$anon$2.run(package.scala:25)
        at java.lang.Thread.run(Thread.java:679)

为什么

编辑

事实证明,最直接的原因是foo是作为私有生成的。我在回答中推测了原因,但我不确定。如果你有一个想法,仍然可以将其作为答案发布


共 (0) 个答案