jeudi 28 avril 2016

How do I access a Java static member from Scala with reflection?

I have an autogenerated Java class that I'm using in a Scala application. Something like:

public class Model123123 extends GenModel {
  public int nclasses() { return 4; }

  // Names of columns used by model.
  public static final String[] NAMES = NamesHolder_Model123123.VALUES;

I can create instances like this

val model = Class
          .forName("Model123123")
          .newInstance()
          .asInstanceOf[GenModel]

I'd like to access the static members of this Java class. I can do it directly, like this:

Model123123.NAMES

but don't understand how to do it via reflection. I've tried:

scala> Class.forName("Model123123").NAMES
<console>:10: error: value NAMES is not a member of Class[?0]
              Class.forName(model_name).NAMES

and

scala> model.getClass.NAMES
<console>:11: error: value NAMES is not a member of Class[?0]
              model.getClass.NAMES

I don't know a ton about Java or scala reflection, so I'm a bit lost. I'm trying to do this via reflection as I will have many classes that subclass the same parent class and I'd like to change the class dynamically at runtime.

Thanks





Aucun commentaire:

Enregistrer un commentaire