Scala反射:如何列出范围中的所有变量?

Scala反射:如何列出范围中的所有变量?,scala,variables,reflection,Scala,Variables,Reflection,如何列出范围/环境/绑定中所有“变量”(不仅仅是变量)的名称和/或值 澄清,在程序/脚本的中间或在RePL的某个点,我需要(1)生成一个列表或(2)打印Scala语句可以访问的所有实体的列表。这在运行时是不可能做到的-至少不是您想要的方式-因为JVM不是组织成一个巨大的符号表,在每次声明后更新,您可以随时查询并查找命名实体(如您所称)(我认为跨语言和跨环境都是如此) 您可以尝试查询确实组织为表的内容,例如类/接口的方法,但在进行查询之前,您必须知道类的完全限定名。为了给您一个简单的示例,根据类加

如何列出范围/环境/绑定中所有“变量”(不仅仅是变量)的名称和/或值


澄清,在程序/脚本的中间或在RePL的某个点,我需要(1)生成一个列表或(2)打印Scala语句可以访问的所有实体的列表。

这在运行时是不可能做到的-至少不是您想要的方式-因为JVM不是组织成一个巨大的符号表,在每次声明后更新,您可以随时查询并查找命名实体(如您所称)(我认为跨语言和跨环境都是如此)

您可以尝试查询确实组织为表的内容,例如类/接口的方法,但在进行查询之前,您必须知道类的完全限定名。为了给您一个简单的示例,根据类加载的工作原理,JVM甚至无法枚举您可以创建的类,因为新类可以动态创建或从某个存储库中检索。再举一个例子,
import
在运行时甚至不存在


你必须缩小你的需求范围。例如,如果你以REPL为目标,你可能能够(但付出的努力将是巨大的)为了修改它的内部数据结构,Similarily,如果你以一个脚本为目标并访问源代码,你可以在理论上用一个插件来修改编译器,它可以完成你需要的工作。ffort和我看不出有什么真正的需要。

这个问题可以从广义上解释,但例如,REPL对
javax.script
和作用域绑定有一些支持:

$ scala
Welcome to Scala version 2.11.2 (Java HotSpot(TM) 64-Bit Server VM, Java 1.8.0_11).
Type in expressions to have them evaluated.
Type :help for more information.

scala> val e = $intp.asInstanceOf[javax.script.ScriptEngine]
e: javax.script.ScriptEngine = scala.tools.nsc.interpreter.ILoop$ILoopInterpreter@2b71fc7e

scala> e.getContext
res0: javax.script.ScriptContext = javax.script.SimpleScriptContext@63c12fb0

scala> e.getContext.getScopes
res1: java.util.List[Integer] = [100, 200]

scala> e.getContext.getBindings(100)
res2: javax.script.Bindings = {}
REPL本身保留一个可以查询的范围,表示自动导入到当前脚本行的当前会话的历史记录:

scala> $intp.replScope
res3: $intp.global.Scope = Scopes(value $intp, value e, value res0, value res1, value res2)
也可以使用REPL的完成机制:

scala> :power
** Power User mode enabled - BEEP WHIR GYVE **
** :phase has been set to 'typer'.          **
** scala.tools.nsc._ has been imported      **
** global._, definitions._ also imported    **
** Try  :help, :vals, power.<tab>           **

scala> reader.completion
res4: scala.tools.nsc.interpreter.Completion = scala.tools.nsc.interpreter.JLineCompletion@68b7bdcb

scala> res4.completer.complete("",0)
res6: scala.tools.nsc.interpreter.Completion.Candidates = Candidates(0,List($intp, $ires0, $ires1, $ires10, $ires11, $ires12, $ires13, $ires14, $ires15, $ires16, $ires17, $ires18, $ires2, $ires3, $ires4, $ires5, $ires6, $ires7, $ires8, $ires9, $r, AND, BLOCK, CASE, DEFAULT, FALSE, IF, LIT, NEW, NOT, NULL, REF, SOME, SelectStart, TRUE, TRY, UNIT, ZERO, analyzer, classOf, completion, e, fn, global, history, intp, isettings, lastRequest, mkTreeFromSelectStart, mkTreeMethods, mkTreeMethodsFromSelectStart, mkTreeMethodsFromSymbol, nullSafe, phased, power, r, reader, repl, replImplicits, res0, res1, res2, res3, res4, returning, scala$tools$nsc$ast$TreeDSL$CODE$$$outer, treedsl, typed, typer, vals))

scala> 

REPL环境(在可能的情况下)通常不同于[Java/运行时]反射(在不可能的情况下)。您需要的是一个能够访问Java的完整源代码的工具。Scala不是那个工具。请参阅JavaC编译器或查看程序转换工具。我感谢大家不要修改我提出的问题。格式更正非常好,澄清非常好。但是如果您想更改问题,请为自己编写一个问题是关于Scala的,不仅仅是REPL。这是一个很好的答案。注意:如果您使用的是Spark REPL,这将不起作用,但您可以只使用$intp。allDefinedNames@TristanReid如果没有投票权,这不是一个很好的答案。根据SO章程,这是不可能的。我认为有人在努力将Spark REPL带回代表处L fold,他们可以提供一个REPL供其他项目扩展。这可能不是这个REPL。你错了。不是所有的好答案都有投票权。顺便说一句,谢谢你这个好答案!
$ scala
Welcome to Scala version 2.11.2 (Java HotSpot(TM) 64-Bit Server VM, Java 1.8.0_11).
Type in expressions to have them evaluated.
Type :help for more information.

scala> 
$intp          broken           enumtest       inheritthewind   maker           oracle        sbtbomb             thingy         
P              bumper           erased         inlined          mangled         orelse        scala               throwgen       
Q              butwhen          exh            inliner          mapeach         org           scallop             thrownull      
SO22581163     bytype           eyeshadow      inner            maqicode        othercase     scrap               tiles          
_root_         callbacks        fany           inputcheck       matchprim       out           scripts             timezone       
a              capture          featureless    intcake          maybeamb        overdone      searchme            tmp            
abjectfuture   cce              ff             interp           maykov          overnullary   selfpub             toString       
absval         cdtest           fielding       interpat         metamac         pathmaker     seqto               tops           
adaptation     charmatch        filloval       intpbind         mkarray         peasy         serialmigration     trial          
akka           choosy           filrdr         intupolated      mksym           pet           serious             tribool        
algedu         classOf          findwidgets    invokeFrom       modtest         petconfig     shapelessed         tricks         
angeldance     classmatch       finf           isInstanceOf     myanno          phyl          simple-swing        trivial        
annee          classy           fixedimp       isanon           mydays          pickit        singleton           tryxform       
annie          cmpprs           fixes          isfun            myintp          pimpin        slider              tstest         
annoconst      coltfred         fixme          isscala          mypkg           pkginvoke     slow                typeref        
annot          com              flib           java             mypriv          plugincp      smtest              tztest         
anymember      compilit         foodir         javafx           nestedmain      plugs         sobral              unapplynull    
anything       convprs          fooplus        javax            netscape        pointers      somatch             unavail        
applied        copier           for29          jbyte            newfrom         pointopt      some_package        unensured      
arrow          corner           formac         jdk              nextcompleted   pos           sortitout           unused         
asInstanceOf   counted          ftw            jex              niolock         poster        sounds              updater        
atrait         countints        funk           jext             noany           pow           specbug             valdef         
autoenum       cr               funkstr        jline            noapp           preferthunk   speck               vec            
auxctor        ctag             futfilter      jmap             nodep           prettycase    splitat             version        
bad-scales     curtest          futuremap      jover            nofeature       primover      stale               vowelshift     
badXlint       cyclic           fval           jperms           nofuture        printer       statik              w              
badaccess      dbadd            gline          junk             noimp           privctor      str2int             warnadapt      
badbob         default-tparam   global         k                noinline        privover      strtyp              weakerr        
badgeneric     delayed          goodbye        kcharex          nointerp        procked       structural-return   welper         
badimp         delayedsignal    gr             keptstar         nonl            protcase      stupid              whose          
badinherit     delineate        grapher        kmap             norec           protval       succinctly          widgets        
badmap         demoapi          groupby        lazyparadox      nosehorn        publicity     sun                 wrappedarray   
badmatch       dep              guiced         lazyside         nothingannot    q             superduper          wtf            
badover        doc              guy            lazysplit        ns              qqparms       sxema               x              
badoverride    dockable         halfinterval   lib              nts             quickly       syncd               xmladd         
badpath        dosth            here           liner            nullgroup       quoterep      syshook             xmlex          
badpkg         doublearrow      hidden         linetest         nullpair        rawj          t1                  xmlregex       
badseal        dummyonly        hiddenimport   linted           nulltype        raws          t1807               xmlreplace     
badstrimp      dynospec         id             linty            nummaker        reader        t5148               xmlsub         
badvargs       earlier          imparted       lit              off             reflectenum   t5589               xmlt           
badvol         eatery           imparter       littlecake       oiler5          replslow      t7121               xxx            
bigmethod      email            impctx         looker           old-and-blue    repro         t7775               zed            
binder         empty            impless        lookit           oldname         required      t8433                              
biterpolator   emptypackage     impmag         lookup           om              sample-foo    tabpane                            
blocking       enclosing        imptest        loopy            oneq            samplewarn    taggedparam                        
blownfuture    enclosingcls     imptrait       macinfer         oops            saver         target                             
bounded        enpatch          include        macvar           optdate         sbt-test      teachers                           

scala>