1

I have a relatively simple object with a method that makes an HTTP request. The request automatically extracts the data according to class type and spits out the necessary object.

The problem is that I can't seem to reference the class dynamically. The code:

object abstractObject extends APIResource {

  def retrieve(clazz: String, key: String) = { 
    request("GET", instanceURL(key)).extract[clazz]
  }

}

clazz defines a type that is to be passed on to extract which allows the request to parse a JSON hash on-the-fly into an object. I need to somehow use that String to dynamically reference the class type and pass it to extract.

Any ideas or will I need to re-architect this?

crockpotveggies
  • 12,682
  • 12
  • 70
  • 140
  • maybe something like `def retrieve[T](key: String) = request("GET", instance(key)).extract[T]` ? – markmarch Jun 08 '12 at 02:04
  • interesting, i got a "missing manifest" compiler error but i never thought about this. that error also brought up this great question http://stackoverflow.com/questions/7294761/why-is-the-manifest-not-available-in-the-constructor perhaps i can get somewhere with it. thanks! – crockpotveggies Jun 08 '12 at 02:27
  • Where do you get your clazz string from? The way you described your problem, there is no possibility but to use reflections (which really isn't what you want). If you are thinking about a API redesign, I'd think about the prototype pattern. When you provide some more informations about your system, I will be able to make an example. – Heinzi Jun 08 '12 at 14:28
  • the clazz string comes from a JSON deserializer. this particular API sends a JSON object that has an embedded object, and the deserializer extracts that object and then contacts the API to verify its authenticity. it's a painful process... – crockpotveggies Jun 08 '12 at 17:47

1 Answers1

1

Types only exist at compile time, so you can't go from a run-time value to a type. Well, you can with Scala 2.10's reflection, which would essentially get the code you need generated at run time, and then executed. You'd need to bundle both compiler and reflection jar files with the application.

However, none of that should be required for what you are proposing. A Class or Manifest object is enough -- though, of course, maybe the API you are using doesn't provide such alternative.

Daniel C. Sobral
  • 295,120
  • 86
  • 501
  • 681