I had to write my own JDK dynamic proxy to provide the ability of dynamic interface implementation. Since I work with akka it has to be written in Scala. But I faced with some pretty strange behavior differs from Java:
object Main extends App {
println(classOf[Message].getDeclaredMethod("msg")
.invoke(Message("Test"), null))
//throws IllegalArgumentException
}
case class Message(message: String){
def msg() = message
}
StackTrace:
Exception in thread "main" java.lang.IllegalArgumentException: wrong number of arguments
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:497)
at Main$.delayedEndpoint$Main$1(Main.scala:2)
at Main$delayedInit$body.apply(Main.scala:1)
at scala.Function0$class.apply$mcV$sp(Function0.scala:34)
at scala.runtime.AbstractFunction0.apply$mcV$sp(AbstractFunction0.scala:12)
at scala.App$$anonfun$main$1.apply(App.scala:76)
at scala.App$$anonfun$main$1.apply(App.scala:76)
at scala.collection.immutable.List.foreach(List.scala:381)
at scala.collection.generic.TraversableForwarder$class.foreach(TraversableForwarder.scala:35)
at scala.App$class.main(App.scala:76)
at Main$.main(Main.scala:1)
at Main.main(Main.scala)
But I in Java it works fine:
public static void main (String[] args) throws java.lang.Exception
{
System.out.println(Message.class.getDeclaredMethod("msg")
.invoke(new Message(), null)); //prints Message
}
public static class Message{
public String msg(){
return "Message";
}
}
Why does Scala throw exception? And how to fix it?
nullargument differently, into its own arguments instead of to mean no arguments. Just remove it from the invocation.