ts.
ts.

Reputation: 10709

obtaining type from type name in scala

After some fiddling with scala I came to that solution for creating new objects from given type

object Entity {

  def get[T <: Entity: ClassManifest]: T = {

      val entity = implicitly[ClassManifest[T]].erasure.getConstructors()(0).newInstance().asInstanceOf[T]

      /** some stuff **/

      entity

  }

}

abstract class Entity {

}

class Implementation extends Entity {

}

and then usage:

var e = Entity.get[Implementation]

My questions

  1. is that ok or there is some different way of doing that (i am using scala 2.9.2 now)?

  2. Is there something like Class.forName which allows to get type from its name? (or more generally, can I use type as variable?)

Upvotes: 1

Views: 513

Answers (2)

dhg
dhg

Reputation: 52681

Alternatively, you could pass the Class[T]:

object Entity {
  def get[T <: Entity](e: Class[T]): T = {
    val entity = e.getConstructors()(0).newInstance().asInstanceOf[T]
    /** some stuff **/
    entity
  }
}

var e1 = Entity.get(classOf[Implementation])

You can use Class.forName, but you would lose type-safety (since the string className could be anything, not just an Entity subclass) and I think your return type would have to be Entity.

Upvotes: 0

Dave Griffith
Dave Griffith

Reputation: 20515

So one of the problems with StackOverflow is that no one is going to give me points for saying "Wow, that's clever. For god's sake don't ever do that or anything like it." Nonetheless, as a senior architect, that appears to be most of my job.

If you are using reflection outside or a library, or as a reason for interacting with a library, you're doing it wrong. So stop it.

Upvotes: 7

Related Questions