1

Is it possible to get a reference to a Scala Object class from Java, using reflection?

To illustrate what I mean, this is the Scala code for doing this (assume MyClass is a Scala Object):

  val runtimeMirror = universe.runtimeMirror(getClass.getClassLoader)
  val module = runtimeMirror.staticModule("MyClass")
  val obj = runtimeMirror.reflectModule(module)
  val realObject: MyInterface = obj.instance.asInstanceOf[MyInterface]

In Java, I successfully loaded the Class, but I can't seem to be able to get an actual reference to the object; calling newInstance() on the class obviously fails since it doesn't have a public constructor.

I've managed to workaround it by getting its constructor by reflection and setting it to be accessible, but that seems like a hack to me.. is there a BKM for doing this sort of thing?

Dan Markhasin
  • 752
  • 2
  • 8
  • 20
  • lots of reflection code does that... `setAcessible(true)` that is. You are already using *reflection*, which is already sort of a hack – Eugene Apr 04 '17 at 14:08
  • Scala's object compiles to 2 `.class` files, one containing only the static forwarder to the implementation (singleton), called `$MODULE` and other one, inner class with `$` appended. See this answer http://stackoverflow.com/a/12785219/4496364. I guess you want the `MODULE$` instance... – insan-e Apr 04 '17 at 14:41
  • @Eugene However, this particular use of `setAccessible` will give wrong results. – Alexey Romanov Apr 04 '17 at 17:02

2 Answers2

1

The comment from insan-e mentioning MODULE$ did the trick.

The code below now works as expected (loading the class from an external jar file):

String className = "MyClass";
File f = new File("C:\\TEMP\\source.jar");
URLClassLoader urlCl = new URLClassLoader(new URL[]{f.toURI().toURL()}, getClass().getClassLoader());
Class c = urlCl.loadClass(className);
Field module = c.getField("MODULE$");
if (module.get(this) instanceof MyInterface) 
{
   MyInterface obj = (MyInterface) module.get(this);
}
Dan Markhasin
  • 752
  • 2
  • 8
  • 20
0

See the answers to this question about the Java-equivalent implementation of Scala objects to understand how Scala objects translate to Java concepts

What is the Java equivalent of a Scala object?

Community
  • 1
  • 1
radumanolescu
  • 4,059
  • 2
  • 31
  • 44