问题
Is it possible to show the full type signature (with erased parameterized types) saved in the bytecode with the new Reflection library?
For example the type
Any => Unit
should be displayed as
"scala.Function1<java.lang.Object,scala.runtime.BoxedUnit>"
because that's the type stored in the bytecode. It is possible to show this type with javap
. First one needs to compile some code with scalac
:
object X {
def m(f: Any => Unit) = f
}
The command javap -c -s -l -verbose X$
shows:
...
const #25 = Asciz (Lscala/Function1<Ljava/lang/Object;Lscala/runtime/BoxedUnit;>;)Lscala/Function1<Ljava/lang/Object;Lscala/runtime/BoxedUnit;>;;
...
public scala.Function1 m(scala.Function1);
Signature: (Lscala/Function1;)Lscala/Function1;
...
The output of javap
is a bit weird I'm more interested to get "Java like" output. Maybe a string which represents the type signature a even better a type which could easily generate this string.
Another example:
package abc
object O {
def x(i: Int)(j: Int) = i+j
}
// type of x should be displayed something like
"int abc.O$.x(int, int)"
Is something like this already supported and if not how to build such an output for any types?
回答1:
Types are already the full type signatures, but they do not include the complete path. For that, you'd have to go to the symbol and get its owner, or something like that.
Every question about the new reflection has been doing that, so if you could be more specific, it would help.
scala> import scala.reflect.runtime.universe._
import scala.reflect.runtime.universe._
scala> typeOf[abc.O.type].member(newTermName("x")).typeSignatureIn(typeOf[abc.O.type])
res0: reflect.runtime.universe.Type = (i: scala.Int)(j: scala.Int)scala.Int
来源:https://stackoverflow.com/questions/11659570/reflection-show-bytecode-type-signature-of-static-types