运行时中某些类型的实例,Scala

运行时中某些类型的实例,Scala,scala,reflection,types,runtime,Scala,Reflection,Types,Runtime,我们的想法是,例如,我们得到了某个对象的类型: val tm = getTypeTag("String here").tpe //> tm: reflect.runtime.universe.Type = java.lang.String // for example I got another val or var, of some type: val tmA: Any = "String here" //> tmA: Any = String here 如何制作tmA.In

我们的想法是,例如,我们得到了某个对象的类型:

val tm = getTypeTag("String here").tpe
//> tm: reflect.runtime.universe.Type = java.lang.String

// for example I got another val or var, of some type:

val tmA: Any = "String here"
//> tmA: Any = String here
如何制作
tmA.InstanceOf(tm)
(它是一种助记码)?'原因
tm
它不是一个类型别名,我们无法准确地生成[tm]实例

已编辑

这里我指的是模拟功能,用于制作一种类型转换

EDITED2

我将自己部分回答我的问题。因此,如果我们有
TypeTags
就很容易了

def tGet[T](t: TypeTag[T], obj: Any): T = obj.asInstanceOf[T]
如果我们只得到
Type
而不是整个
TypeTag[T]
,情况就更糟了

您可以使用来反映实例:

val mirror = runtimeMirror(getClass.getClassLoader)

def isTm(a: Any) = mirror.reflect(a).symbol == tm.typeSymbol
然后:

scala> isTm("String here": Any)
res0: Boolean = true

scala> isTm(List("String here"): Any)
res1: Boolean = false

不过,我不认为我必须告诉您这是一个多么糟糕的主意。

您只需要在变量之后使用变量的type属性。 例如,您可以编写:

val h=“你好” val b:Any=“hhh”

val stringB:String=b.asInstanceOf[h.type]


println(stringB)

thx回复!没错,这不是个好主意。但我的想法是,我百分之百确定,这个物体是那种类型的。Mb我的问题中有一点错误,但我的意思是
.asInstanceOf(tm)
,所以要做一种铸造。。例如
tm
ru.Type=String
,而函数
myAsInstanceOf(tm)
实际上与
asInstanceOf[String]
相同。哦,我当时确实误解了
InstanceOf
的意思是
isInstanceOf
。我想你需要一个类型标签(或宏)来进行演员表演——我会在有机会的时候试着整理一个答案。谢谢!那太好了。。。如果cource可能的话,我会尽量避免这种情况,并在这里发布。但他试图将类型转换为
type
值(或
TypeTag
值)表示的类型,而不是某个给定值的类型。