我如何获得 ClassOf 一个 ClassTag? [英] How do I get the classOf a ClassTag?

查看:45
本文介绍了我如何获得 ClassOf 一个 ClassTag?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这不起作用 - 有什么办法可以让我的代码保持通用化并以某种方式反映 ClassOf 一个 ClassTag 吗??

This doesn't work - is there any way I can keep my code generified and somehow reflect the classOf a ClassTag??

class Foo[T : reflect.ClassTag] { def foo = classOf[T] }

<console>:7: error: class type required but T found
   class Foo[T : reflect.ClassTag] { def foo = classOf[T] }

看来这应该可行,但唉:(

It seems this should work but alas :(

推荐答案

是的,这是可能的.

class Foo[T: reflect.ClassTag] {
  def ctag = implicitly[reflect.ClassTag[T]]
  def foo: Class[T] = ctag.runtimeClass.asInstanceOf[Class[T]]
}

或更短:

class Foo[T](implicit ctag: reflect.ClassTag[T]) {
  def foo: Class[T] = ctag.runtimeClass.asInstanceOf[Class[T]]
}

这篇关于我如何获得 ClassOf 一个 ClassTag?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆