Consider the following code:
object U { def foo(s:String) = true }
val boolType = Class.forName("java.lang.Boolean")
val retType = U.getClass.getMethods.find(_.getName == "foo").get.getReturnType
boolType == retType // evaluates to false (*)
println (boolType) // prints "class java.lang.Boolean"
println (retType) // prints "boolean"
I would like retType to match with boolType in the line marked (*). How do I automatically equate classes of boxed and unboxed types?
[Edit:] I don’t think this is the best solution, but one way is to make the comparison
retType.getCanonicalName == "boolean"
[Edit2:] The context: I am writing some code to automatically invoke a method based on a form name. The code should extract the return types etc from the method and return the appropriate answer. As an example, the following snippet is used:
object someObject {}
val validTypes:Array[Class[_]] = Array(Class.forName("java.lang.String"),
someObject.getClass,
Class.forName("java.lang.Boolean"))
object U { def foo(s:String) = true } // can contain more methods
def getRetType(name:String) =
U.getClass.getMethods.find(_.getName == name).get.getReturnType
println ("Type is "+(if (validTypes.contains(getRetType("foo"))) "valid" else "invalid"))
When Java reflection wants to represent a primitive return type, it uses
Classinstances that are not the same as the wrapper classes. So in Java, abooleanreturn type is represented by ajava.lang.Boolean.TYPE(which in Java is also accessible asboolean.class, and in Scala asclassOf[Boolean]).So you want
Edit : I guess that comparing with
classOf[Boolean]would be a less JVM specific solution.