简体   繁体   English

加载名称冲突的Groovy类

[英]Loading groovy classes with conflicting names

I use GroovyScriptEngine inside my Java application to load code dynamically from different sources. 我在Java应用程序中使用GroovyScriptEngine来从不同来源动态加载代码。 Let's say I have two folders sources_A\\ and sources_B\\ . 假设我有两个文件夹sources_A\\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. 在每个文件夹中,我都有Groovy包和类,希望在运行时任意实例化。

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 错误:文件bar.groovy中的foo方法中第**行的参数类型不匹配

(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? 通过某种方式使两个不同引擎的对象协同工作的双引擎解决方案?

Java (and Groovy) classloader identifies a class by its fully qualified name and can load it only once. Java(和Groovy)类加载器通过其完全限定的名称标识类,并且只能加载一次。 So, no, you can't load 2 classes of the same name (only one will be loaded). 因此,不可以,您不能加载2个同名的类(仅可以加载一个)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM