简体   繁体   English

Scala-从Java中反射性地调用私有静态方法

[英]Scala - reflectively invoke private static method from Java

I'm trying to take a private static method from a Java class and invoke it in Scala. 我正在尝试从Java类中获取private static方法,并在Scala中调用它。 Here's the code I have so far: 这是我到目前为止的代码:

val blockClass = classOf[Block]
val aMethod: Method = blockClass.getDeclaredMethod("a", Integer.TYPE, classOf[String], classOf[Block])
aMethod.setAccessible(true)

aMethod.invoke(null, 145, "anvil", anvilPatch)

When I try to compile this, however, I get this error: 但是,当我尝试对此进行编译时,出现以下错误:

Error: the result type of an implicit conversion must be more specific than AnyRef
aMethod.invoke(null, 145, "anvil", null)
                     ^

That 145 is supposed to be a Java int , and Integer.TYPE is the only thing I could think of to get a Java int . 145应该是Java int ,而Integer.TYPE是我想到的唯一获得Java int

Any ideas? 有任何想法吗?

不知道为什么会发生错误,但是可以通过将145显式地强制转换为AnyRef (与Object相同)来解决:

aMethod.invoke(null, 145.asInstanceOf[AnyRef], "anvil", anvilPatch)

Instead of using Integer.TYPE , try using classOf[Int] . 代替使用Integer.TYPE ,尝试使用classOf[Int] This will get you the class object of Scala's Int type. 这将为您提供Scala的Int类型的类对象。

val aMethod: Method = blockClass.getDeclaredMethod("a", classOf[Int], classOf[String], classOf[Block])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM