0

I use GroovyScriptEngine inside my Java application to load code dynamically from different sources. Let's say I have two folders sources_A\ and sources_B\.

GroovyScriptEngine engine = new GroovyScriptEngine(new String[]{
    "sources_A", "sources_B"
});

Within each folder I have Groovy packages and classes that I wish to instantiate arbitrarily at runtime.

Problem: Some of these classes have the same (full) name in both folders.

So there is an ambiguity when I run:

engine.loadScriptByName("some.package.SomeClass").newInstance()

Of course, I could create two different engines:

GroovyScriptEngine engine_A = new GroovyScriptEngine(new String[]{"sources_A"});
GroovyScriptEngine engine_B = new GroovyScriptEngine(new String[]{"sources_B"});

But then I run into issues when two objects instantiated from these two different engines have to interact with each other:

object_from_A.someMethod(object_from_B);

Error: argument type mismatch at line ** in method foo in file bar.groovy

(Needless to say that there is no type mismatch: the object has the right type but is not recognized due to the different engine)

In short, do you have a solution to either:

  • The one-engine solution with some way to disambiguate which source folder is used?
  • The two-engine solution with some way to have objects from the two different engines to work together?
Eric Leibenguth
  • 4,167
  • 3
  • 24
  • 51

1 Answers1

0

Java (and Groovy) classloader identifies a class by its fully qualified name and can load it only once. So, no, you can't load 2 classes of the same name (only one will be loaded).

JBaruch
  • 22,610
  • 5
  • 62
  • 90
  • I do want to load one version once and for all. The problem is that I have no control over which version is loaded. Isn't there a way to tell the classloader which of the two versions It should load? – Eric Leibenguth Jul 26 '16 at 16:33
  • Nope. You can't control it. Good news are since you load your classes in code, just incorporate the selection logic in your code and create the engine with only the right source code directory. – JBaruch Jul 26 '16 at 16:36