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?

3
  • lots of reflection code does that... setAcessible(true) that is. You are already using reflection, which is already sort of a hack Commented Apr 4, 2017 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 stackoverflow.com/a/12785219/4496364. I guess you want the MODULE$ instance... Commented Apr 4, 2017 at 14:41
  • @Eugene However, this particular use of setAccessible will give wrong results. Commented Apr 4, 2017 at 17:02

2 Answers 2

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);
}
Sign up to request clarification or add additional context in comments.

Comments

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?

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.