0
votes

I have tens of JSON fragments to parse, and for each one I need to get an instance of the right parser. My idea was to create a config file where to write the name of the class to instantiate for each parser (a kind of map url -> parser) . Getting back to your solution, I cannot call the method I implemented in each parser if I have a pointer to Any. I suppose this is a very common problem with a well-set solution, but I have no idea what the best practices could be.

I really have no experience with Java, Reflection, Class Loading and all that stuff. So, can anyone write for me the body of the method below? I need to get an instance of a class passed as String (no arguments needed for the constructor, at least so far...)

def createInstance(clazzName: String) = {
  // get the Class for the given clazzName, e.g. "net.my.BeautifulClazz"

  // instantiate an object and return it
}

Thanks, as usual...

1

1 Answers

1
votes

There is a very simple answer:

scala> def createInstance(clazzName: String) = Class.forName(clazzName).newInstance
createInstance: (clazzName: String)Any

scala> createInstance("java.lang.String")
res0: Any = ""

If it works for you, everything is fine. If it don't, we have to look into your class loader. This is usually the point when things will get dirty.

Depending in what you want to do, look into:

  1. The cake pattern, if you want to combine your classes during compile time
  2. OSGi when you want to build a plugin infrastructure (look here for a very simple example)
  3. Google guice, if you really need dependency injection (e.g. when mixing Scala and Java code) and the cake pattern does not work for you