Skip to content

Instantly share code, notes, and snippets.

@yamashiro
Created July 6, 2012 09:01
Show Gist options
  • Save yamashiro/3059076 to your computer and use it in GitHub Desktop.
Save yamashiro/3059076 to your computer and use it in GitHub Desktop.
ScalaからJavaをリフレクションで呼び出すテスト
package study
import scala.util.control.Exception._
import org.specs2.mutable.Specification
class JavaCallSpec extends Specification {
def callJavaCode[T](v:Any, methodName:String)(implicit callCm: ClassManifest[T]): Any = {
println(v.getClass)
val m = v.getClass match {
case c if c == classOf[Integer] => {
allCatch withApply { (t: Throwable) =>
callCm.erasure.getDeclaredMethod(methodName, classOf[Int])
} apply {
callCm.erasure.getDeclaredMethod(methodName, classOf[Integer])
}
}
case c if c == classOf[String] => callCm.erasure.getDeclaredMethod("resolve", v.getClass)
case _ => throw new Exception()
}
m.invoke(null, v.asInstanceOf[Object]).asInstanceOf[AnyVal]
}
"validCode " should {
"string" in {
callJavaCode[JavaCallTarget]("string", "resolve").asInstanceOf[String] must_== "string"
}
"100 as int" in {
callJavaCode[JavaCallTarget](100, "resolve").asInstanceOf[Int] must_== 100
}
"100 as java.langInteger" in {
callJavaCode[JavaCallTarget](100, "resolveInteger").asInstanceOf[Int] must_== 100
}
}
}
package study;
public class JavaCallTarget {
public static int resolve(int hoge) {
System.out.println("resolveInt");
return hoge;
}
public static String resolve(String hoge) {
System.out.println("resolveString");
return hoge;
}
public static int resolveInteger(int hoge) {
System.out.println("resolveInt");
return hoge;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment