What is a ScalaSignature?

2019-07-20 22:34发布

问题:

When decompiling Scala files to Java code, one often comes across classes that are annotated with the ScalaSignatures. These seem to only have one annotation value, a somewhat encoded String. Why does the Scala Compiler create such an odd construct, instead of using custom Attributes in the class file?

回答1:

From Storage of pickled Scala signatures in class files:

The legacy method for storing signatures as attributes is simultaneously more elegant, more compact (about 15%) and simpler than that using annotations. However, to access the pickled signature in attributes requires obtaining and parsing the entire class file. Because annotations are recognized by the JVM, the new method allows retrieving pickled signature bytes directly from within a running Scala program by using Java reflection.

The new method is part of an ongoing development to write a good Scala reflection library. Java reflection views Scala programs in a simplified Java-centric way. To give a Scala-centric view of the reflected program, information provided by Java reflection must be completed with information found in Scala signatures. The legacy storage method would have required all class files to be parsed again — the JVM has parsed them already and exposes most of their content through reflection. The new storage method allows accessing pickled Scala signatures in the same way than other reflective information is obtained, making the new Scala reflection library simpler and faster.

Whilst the Scala reflection library will not be part of the 2.8 release, it is desirable that existing 2.8 class files are compatible with the new reflection library when it becomes available. Furthermore, since 2.8 class files are incompatible with those of 2.7 in any case, changing the method of storing signatures in 2.8 will not require another binary-incompatible class file format change shortly after.