Given is a Java method that returns java.lang.Object
s for a given string. I'd like to wrap this method in a Scala method that converts the returned instances to some type T
. If the conversion fails, the method should return None
. I am looking for something similar to this:
def convert[T](key: String): Option[T] = {
val obj = someJavaMethod(key)
// return Some(obj) if obj is of type T, otherwise None
}
convert[Int]("keyToSomeInt") // yields Some(1)
convert[String]("keyToSomeInt") // yields None
(How) Can this be achieved using Scala's reflection API? I am well aware that the signature of convert
might have to be altered.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…