考虑以下法典:
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"))