How to get the runtime class of a parameterized type in a Scala attribute

I am trying to implement a Scala trait that handles the details of interacting with a Java library that requires us to create

I want to do something like:

trait SomeTrait[A] extends JavaAPI {
  def foo = {
    callApi(classOf[A])
  }

  override def bar = {
    foo
  }
}

Note that the bar actually overrides the method from the base class, so I cannot change its signature.

I tried several options with Manifests, etc., but can't make it work. Is there a way to get the runtime class of a parameterized type?

+5
source share
4 answers

This scent should do the trick:

trait SomeTrait[A] {
  def foo(implicit ev: Manifest[A]) = {
    callApi(ev.erasure)
  }
}

update - . , .

, ! , , , , -...

trait SomeTrait {
  def ev: Manifest[_] //abstract
  def foo = println(ev.erasure)
}

//this `ev` provides the implementation, note that it MUST be a val, or var
class Concrete[T](implicit val ev: Manifest[T]) extends SomeTrait

.

+10

- , . , . .

trait SomeTrait[A] {
  implicit def manifesto: Manifest[A]

  def foo = println(manifest[A].erasure)
}
object SomeTrait {
  def apply[A: Manifest] : SomeTrait[A] = new SomeTrait[A] { def manifesto = manifest[A] }
}
+5

- , . , . . , .

class SomeTrait[A](implicit ev: Manifest[A]) extends JavaApi {
  def foo = {
    callApi(ev.erasure)
  }


  override def bar = {
    foo
  }
}
+4
source

It may be a little awkward to do this in your code, but you can do it

trait SomeTrait[A] extends JavaAPI {
  def objType: Class[A]
  def foo = {
    callApi(objType)
  }

  override def bar = {
    foo
  }
}

object SomeImplementation with SomeTrait[SomeObject] {
  val objType: Class[SomeObject] = classOf[SomeObject]
}

I know this is a bit verbose, but the way I solved this problem. I hope to find a better solution in the future, but this is what I am using now. Let me know if this helps you.

0
source

All Articles