Created
July 6, 2012 09:01
-
-
Save yamashiro/3059076 to your computer and use it in GitHub Desktop.
ScalaからJavaをリフレクションで呼び出すテスト
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | |
} | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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