简体   繁体   English

Scala中的Java反射

[英]Java Reflection in Scala

I am trying to get a simple java reflection program working in Scala, and seem to be missing something ... 我正在尝试让一个简单的Java反射程序在Scala中运行,并且似乎缺少了一些东西...

scala> val cl = new URLClassLoader(Array(new File("Hi.jar").toURI.toURL), getClass.getClassLoader)
cl: java.net.URLClassLoader = java.net.URLClassLoader@3c7b137a

scala> val c = cl.loadClass("Hi")
c: Class[_] = class Hi

scala> val m = c.getMethod("run")
m: java.lang.reflect.Method = public void Hi.run()

scala> m.invoke()
<console>:21: error: not enough arguments for method invoke: (x$1: Any, x$2: Object*)Object.
Unspecified value parameters x$1, x$2.
       m.invoke()
               ^

What am I missing, as the prior line has indicated - 正如前一行所指出的,我缺少什么?

public void Hi.run()

What exactly is it expecting for the two arguments? 这两个参数到底期望什么?

Scala is telling you exactly what your problem is: invoke needs 1+ parameters! Scala准确地告诉您您的问题是什么:invoke需要1个以上的参数!

See the java doc : 请参阅java doc

invoke(Object obj, Object... args) invoke(Object obj,Object ... args)

Invokes the underlying method represented by this Method object, on the specified object with the specified parameters. 在具有指定参数的指定对象上调用此Method对象表示的基础方法。

So, you have to provide at least one argument - a reference to the object (or class) you want to call that method on! 因此,您必须至少提供一个参数-对要调用该方法的对象(或类)的引用! As Hi.run() seems to be static, you would want to use your c as only argument to your call. 由于Hi.run()似乎是静态的,因此您希望将c用作调用的唯一参数。

The following arguments would be the actual parameters that your "reflected" method expects. 以下参数将是您的“反射”方法所期望的实际参数。 In your case, no further arguments. 在您的情况下,没有其他争论。

Long story short: you better keep the excellent tutorials from Oracle on reflection close to your scala console while experimenting. 长话短说:在实验时,最好将Oracle的优秀教程放在您的Scala控制台附近进行反思。 If you try to learn "reflection" by trial&error; 如果您尝试通过试错来学习“反思”; I guarantee you: a lot of frustrating trials with many strange errors. 我向您保证: 很多令人沮丧的尝试,其中包含许多奇怪的错误。 Really: the reflection API is not very forgiving when you don't know what you are doing; 确实:当您不知道自己在做什么时,反射API并不是很宽容。 even the slightest mistakes can lead to very unexpected results. 即使是最轻微的错误也会导致非常意外的结果。

There is nothing specific to Scala there. 那里没有特定于Scala的东西。 Method.invoke requires the at least one argument being the instance on which it's applied (or null for a static method). Method.invoke要求至少一个参数是应用它的实例(对于static方法为null )。

In Scala, you can use structural typing for such simple case. 在Scala中,可以将结构化类型用于这种简单情况。

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

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