Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
223 views
in Technique[技术] by (71.8m points)

Finding type parameters via reflection in Scala 2.10?

Using type tags, I'm able to see the parameters of some type:

scala> import scala.reflect.runtime.universe._
import scala.reflect.runtime.universe._

scala> typeOf[List[Int]]
res0: reflect.runtime.universe.Type = List[Int]

But I just can't quite figure out how to programmatically get that "Int" out of there, in a general way.

(I've been wandering around in REPL for an hour now, trying permutations on Type, to see what I can obtain from it... I get a lot of things which indicate this is a "List", but good luck on finding that "Int"! And I don't really want to resort to parsing the toString() output...)

Daniel Sobral has an excellent (as usual) quick overview here, in which he gets tantalizingly close to what I'm looking for, but (apparently) only if you happen to know, for that particular class, some specific method whose type can be interrogated:

scala> res0.member(newTermName("head"))
res1: reflect.runtime.universe.Symbol = method head

scala> res1.typeSignatureIn(res0)
res2: reflect.runtime.universe.Type = => Int

But I'm hoping for something more general, which doesn't involve rooting around in the list of declared methods and hoping that one of them will capture (and thus divulge) the tag's current type information somewhere.

If Scala can so easily print "List[Int]", why on earth is it so hard to discover that "Int" part of that -- without resorting to string pattern matching? Or am I just missing something really, really obvious?

scala> res0.typeSymbol.asInstanceOf[ClassSymbol].typeParams
res12: List[reflect.runtime.universe.Symbol] = List(type A)

scala> res12.head.typeSignatureIn(res0)
res13: reflect.runtime.universe.Type = 

Grr...

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Starting with Scala 2.11, you can simply use:

yourGenericType.typeArgs.head

See the macros changelog point number 14.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...