2

I'm writing a Scala wrapper over some Java code with a method signature like method(cl: Class[_], name: String) and many getClass methods in code looks not good:

Creator.create(getClass, "One")
Creator.create(getClass, "Two")
Creator.create(getClass, "Three")
Creator.create(getClass, "Four")

So can we somehow get enclosing class implicitly like Creator.create("some name")?

4lex1v
  • 21,367
  • 6
  • 52
  • 86
  • Can you explain better your question? I strongly suggest you to avoid using reflection.... – Edmondo Jan 25 '13 at 09:26
  • @Edmondo1984 I'm interested in simple solution how to get class implicitly, and write method("some name") instead of method(getClass, "some name"), and the solution with ClassTags like method[SomeClass]("some name") doesn't look like a better aproach =) – 4lex1v Jan 25 '13 at 10:21

1 Answers1

3

Answer 1.

In general I warmly discourage reflection. However, if you really want to do it, in Scala 2.9.1 you can use Manifest

def create[T:Manifest](name:String) = {
   val klass:Class[_] = t.erasure
}

In scala 2.10 you should have a look to TypeTag.

Answer 2.

However, as I already said, the right approach would not be to use class but implicit builders

trait Builder[T]{
     def build(name:String):T
}

def create[T](name:String)(implicit builder:Builder[T]) = {
      builder.build(name)
}

in that way you can limit what you can create by importing only the right implicits in scope, you won't rely on reflection and you won't risk to get horrible RuntimeExceptions

Post comment answer

If your point is to avoid calling getClass at each invocation, you can do the following

def create(name:String)(implicit klass:Class[_]) {

}

And you can call it this way

implicit val klass1 = myInstance.getClass
create("hello")
create("goodbye")
Edmondo
  • 19,559
  • 13
  • 62
  • 115
  • 1
    Yea, i've also thought about ClassTags, but in this case, as you've sad, i have to use reflection and repeating method[Classname](param) isn't better then just call method(getClass, param) – 4lex1v Jan 25 '13 at 10:19