I have
trait T
class C extends T
compiled to .class files. And the piece of code below to load them:
val loader = ScalaClassLoader fromURLs (/* List[URL] */)
val classB = loader.tryToInitializeClass("B") getOrElse (/* throw something */)
println(classB.asInstanceOf[Class[_]].getInterfaces)开发者_运维问答
When I run the loading code in Scala interpreter, the result is
res1: Array[java.lang.Class[_]] = Array(interface T, interface scala.ScalaObject)
but when the loading code compiled into .class files and run I got
[Ljava.lang.Class;@1b8e059
Please tell me how to have the compiled loading code yield the result as fine as on the interpreter.
Are you sure you executed the println in the interpreted session? Because the first result you write looks suspiciously like the interpreter displaying the result of just
classB.asInstanceOf[Class[_]].getInterfaces)
, without the println (res1 is very telling)
On the other hand, the cryptic [Ljava.lang.Class;@1b8e059 is the toString of an Array. So your problem is just that, toString. If you do something like println(yourResult.mkString(", "))
, that should be much better. In the REPL, results displays are better than plain toString
Array(interface T, interface scala.ScalaObject)
and [Ljava.lang.Class;@1b8e059
are the same type of object, just printed out in different ways.
Array[Class[_]] gets printed out like [Ljava.lang.Class;@1b8e059 when you call the toString on it.
Try the following:
scala> val f = Array[Class[_]](classOf[Map[String, String]], classOf[Object])
f: Array[java.lang.Class[_]] = Array(interface scala.collection.immutable.Map, class java.lang.Object)
scala> f.toString
res1: java.lang.String = [Ljava.lang.Class;@407e62
The REPL is being helpful when it prints out the value of an expression. If you want to print out a useful string in your compiled code, for example:
scala> f.toList.toString
res4: String = List(interface scala.collection.immutable.Map, class java.lang.Object)
The line
res1: Array[java.lang.Class[_]] = Array(interface T, interface scala.ScalaObject)
does not come from your println
expression, it comes from the REPL. If an entered expression returns anything except Unit
. The REPL prints the name, type and result of the toString
method of that object.
name: Type = from toString
精彩评论