反射:显示静态类型的字节码类型签名 [英] Reflection: Show bytecode type signature of static types

查看:64
本文介绍了反射:显示静态类型的字节码类型签名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以使用新的反射库显示保存在字节码中的完整类型签名(带有已擦除的参数化类型)?

Is it possible to show the full type signature (with erased parameterized types) saved in the bytecode with the new Reflection library?

例如类型

Any => Unit

应显示为

"scala.Function1<java.lang.Object,scala.runtime.BoxedUnit>"

因为这是存储在字节码中的类型.可以使用 javap 来显示这种类型.第一个需要用 scalac 编译一些代码:

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
}

命令 javap -c -s -l -verbose X$ 显示:

...
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;
...

javap 的输出有点奇怪我更感兴趣的是获得类似 Java"的输出.也许一个代表类型签名的字符串更好是一个可以轻松生成这个字符串的类型.

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.

另一个例子:

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?

推荐答案

类型已经是完整的类型签名,但它们不包括完整的路径.为此,您必须前往符号并获取其所有者或类似内容.

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

这篇关于反射:显示静态类型的字节码类型签名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆