简体   繁体   中英

Java Reflection in Scala

I am trying to get a simple java reflection program working in Scala, and seem to be missing something ...

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!

See the java doc :

invoke(Object obj, Object... args)

Invokes the underlying method represented by this Method object, on the specified object with the specified parameters.

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.

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. 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; even the slightest mistakes can lead to very unexpected results.

There is nothing specific to Scala there. Method.invoke requires the at least one argument being the instance on which it's applied (or null for a static method).

In Scala, you can use structural typing for such simple case.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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