[英]How to list all fields with a custom annotation using Scala's reflection at runtime?
[英]Scala Reflection: How to list all variables in scope?
如何在范圍/環境/綁定中列出所有“變量”(不僅僅是變量)的名稱和/或值?
為了澄清,在程序/腳本的中間或在REPL的某個點,我需要(1)生成列表或(2)打印可由Scala語句訪問的所有實體的列表。
這個問題可以被廣泛地解釋,但是例如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控制台中的單個選項卡提供自動完成功能,此處顯示當前目錄中的所有垃圾,默認情況下位於類路徑上:
$ 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>
這在運行時是不可能的 - 至少不是你想要的方式 - 因為JVM沒有被組織為在每個語句之后更新的巨大符號表,你可以隨時查詢並找到命名實體 ,就像你調用它們一樣(我認為這在語言和環境中都是如此)。
您可以嘗試查詢確實組織為表的內容,例如類/接口的方法,但在進行查詢之前必須知道類的完全限定名稱。 為了給您一個快速示例,根據類加載的工作原理,JVM甚至無法枚舉您可以創建的類,因為新的可以動態創建或從某個存儲庫中檢索。 再舉一個例子, import
在運行時甚至不存在......
你必須縮小你的要求。 例如,如果您定位REPL,您可能(但努力將是巨大的)修改它以便混亂其內部數據結構。 類似地,如果您定位腳本並且可以訪問源代碼,理論上您可以使用插件來修改編譯器,從而完成所需的工作。 請注意,我只提到了這些東西,但從不考慮自己做這樣的事情,因為這需要付出很多努力,我看不出任何真正的需要。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.