如何在範圍/環境/綁定中列出所有「變量」(不僅是變量)的名稱和/或值?我需要(1)生成一個列表或者(2)打印一個Scala可以訪問的所有實體的列表聲明。Scala反射:如何列出範圍內的所有變量?
回答
在運行時這是不可能的 - 至少不是你想要的方式 - 因爲JVM沒有組織成每個語句後更新的符號的巨大表格,您可以隨時查詢並找到名稱爲的實體 ,就像你給他們打電話一樣(我認爲這是跨語言和環境的)。
您可以嘗試查詢確實組織爲表格的內容,例如類/接口的方法,但在之前您必須知道類別的完全限定名稱。爲了給你一個快速的例子,根據類加載的工作原理,JVM甚至無法枚舉你可以創建的類,因爲新的類可以實時創建或從某個存儲庫檢索。再舉一個例子,import
在運行時不存在...
您必須縮小您的需求。例如,如果您定位REPL,那麼您可能會修改它以混淆其內部數據結構(但努力會很大)。類似地,如果你的目標是一個腳本並且有權訪問這些源代碼,那麼理論上你可以用一個插件來修改編譯器,它可以完成你所需要的工作。被警告我只提到這些事情,但不會考慮自己做這樣的事情,因爲這需要很大的努力,我看不到任何真正的需要。
的問題大致可以理解,但例如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 = [email protected]
scala> e.getContext
res0: javax.script.ScriptContext = [email protected]
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 = [email protected]
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控制檯的單一選項卡提供自動完成功能,在這裏顯示了我的當前目錄下所有的垃圾,這是在類路徑默認:
$ 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>
這是一個很好的答案。注意:如果你使用的是Spark REPL,這將不起作用,但你可以使用$ intp.allDefinedNames – 2015-02-13 17:15:06
@TristanReid如果沒有upvotes,它不會是一個好的答案。根據SO章程,這是不可能的。我認爲有必要將Spark REPL帶回到REPL文件中,這樣他們可以爲其他項目提供REPL文件進行擴展。這可能不是這個REPL。 – 2015-02-13 21:08:47
你錯了。並非所有優秀的答案都有提升。順便說一句,感謝這個偉大的答案! – asgs 2016-11-21 17:15:24
- 1. Genshi - 如何打印範圍內的所有變量
- 2. 如何列出我的wifi範圍內的所有設備iphone
- 3. Scala的變量範圍問題
- 4. 範圍內的變量
- 5. 函數範圍內的變量變量
- 6. 在變量範圍內的Perl變量
- 7. 超出範圍的變量?
- 8. 如何將變量移出範圍?
- 9. Unix shell腳本 - 打印範圍內的所有可用變量
- 10. scala內部變量的範圍case case guard
- 11. 變量不在範圍內
- 12. 循環內變量範圍
- 13. 反映方法範圍變量的Java
- 14. Java變量超出範圍
- 15. MySQL變量超出範圍
- 16. 如何查看所有範圍變量的內存使用情況
- 17. 如何使範圍變量?
- 18. VB .Net 2008 - 列出當前在範圍內的所有對象?
- 19. Ansible變量列表範圍
- 20. Tensorflow:如何初始化給定變量範圍中的所有變量
- 21. 如何範圍變量保留所有子程序
- 22. 範圍變量
- 23. 變量範圍
- 24. 變量範圍
- 25. 變量範圍
- 26. 變量範圍
- 27. 變量範圍
- 28. 有沒有辦法看到當前範圍內的所有變量?
- 29. 如何計算全局範圍內全局變量的數量?
- 30. 反向地理編碼半徑範圍內的所有地址
的REPL環境中(在此可是可能的)與[Java /運行時]反射通常不同(如果這是不可能的)。 – user2864740 2014-09-01 21:41:56
您需要的是一個可以訪問Java完整源代碼的工具。斯卡拉不是那種工具。請參閱JavaC編譯器,或查看程序轉換工具。 – 2014-09-01 22:44:20
我會感謝人們不要修改我問的問題。格式更正很好,澄清很好。但如果你想改變這個問題,請爲自己寫一個問題。這個問題一般是關於Scala,而不僅僅是REPL。 – 2014-09-01 23:13:56