Reflection: Show bytecode type signature of static types

两盒软妹~` 提交于 2019-12-24 03:20:04

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!