Reputation: 331
I have a requirement where I need to send from java or scala class a 3rd party class name to an API which I am writing in scala . From that (3rd party) class name I have to instantiate its object (which might have a parameterized constructor as well) and call its corresponding methods . I made attempts but I am not very well clear with the complete reflection working so it looks like this for now:
External (java/scala) class accessing the API :
class AnyRandomClass{
MyAPI api = new API();
api.getThirPartyObject(ThirdPartyClassName);
}
Here is the attempt to write the scala API :
package mypckg
import scala.reflect.runtime._
import scala.reflect.runtime.universe._
class MyAPI{
def getThirdPartyObject ={
val u = universe
val m = u.runtimeMirror(getClass.getClassLoader)
//throws error : type staticClass is not a member of mypckg.MyAPI.u.Mirror
m.runtimeClass(typeOf[m.staticClass(clazz.getName).selfType].typeSymbol.asClass)
}
}
Please help me understand where am I going wrong here , also whats the correct and better way to do it .
Upvotes: 2
Views: 1141
Reputation: 170713
I have a requirement where I need to send from java or scala class a 3rd party class name to an API which I am writing in scala . From that (3rd party) class name I have to instantiate its object (which might have a parameterized constructor as well) and call its corresponding methods
You don't need a TypeTag
for this. Just using Java reflection:
val constructors = clazz.getConstructors
// see also getConstructor, getDeclaredConstructors, and getDeclaredConstructor
val constructor = // select the constructor you need
constructor.newInstance(parameters)
// etc
If you do need to use Scala reflection, ClassTag
should be enough and trivial to get:
ClassTag(clazz)
Upvotes: 1