jeudi 17 mars 2016

What is a reliable way to find a Scala type's companion object via Java reflection?

I'm writing Java (not Scala) code, where I have a Java Class reference, referring to a Scala type T:

trait T {}

I would now like to discover the Java Class reference, and the singleton instance that corresponds to object T by using Java reflection only, and then call a method in that companion object.

object T {
  def someMethod : String = "abc";
}

I have reverse engineered the generated Scala code to write the following Java code:

Class<?> traitClass = ...;
Class<?> companionClass = Class.forName(traitClass.getName() + "$");
Field module = companionClass.getField("MODULE$");
Object companion = module.get(companionClass);
String abc = (String) companionClass.getMethod("someMethod").invoke(companion);

This doesn't appear very robust - it might change any time with future Scala compilers. Is there a more robust way? I'm also open to calling Scala API (from Java) to discover the companion instance.





Aucun commentaire:

Enregistrer un commentaire