I'm considering using the new Type Dynamic, but find that an obvious use case is not well implemented. I'm trying to create convenience wrappers for an object-oriented database. It suffers from casting and usablity issues, because it serializes and deserializes objects (it's methods return Object).
First question: The get method of my database deserializes an object of type A. Althought A has a method a() and I may know at a given moment, that I have an A, i can't call a(), since java only sees Object. Will the Dynamic mechanism try for me if the "underlying" object actually has that method, or do I have to deal with that in applyDynamic myself? I tried it out in the REPL, doesn't seem to do that for me. If I do have to check for myself, what is the easiest way (using scala's new reflection or not), to check if that object has method "methodname" and if yes invoke it.
Scared off by this https://stackoverflow.com/a/11056410/703862 I fall back to java's reflection, which does the method invocation part quite easily.
I come up with this:
scala> import java.lang.reflect.Method
import java.lang.reflect.Method
scala> class DynTest3 extends Dynamic {
| def pee():String = "yuppie"
| def execSucced(method: Method, args: Any*):Boolean = return try{method.invoke(args); true} catch { case e: Exception => false }
| def applyDynamic(methodName : String)(args: Any*){
| val succed = classOf[DynTest3].getDeclaredMethods.filter(m => m.getName() == methodName).exists(m => execSucced(m))
| if (!succed)
| throw new java.lang.NoSuchMethodException
| }
| }
defined class DynTest3
but:
scala> val y: Object = new DynTest3
y: Object = DynTest3@74c74b55
scala> y.asInstanceOf[Dynamic].pee()
<console>:11: error: value applyDynamic is not a member of Dynamic
y.asInstanceOf[Dynamic].pee()
So basically, this doesn't work, even if I cast to Dynamic. Casting to Dynamic already would make the whole thing useless, since I want to save the user from casting. But maybe one could create an implicit conversion any2Dynamic...
Any hints?