如何在隔离的类加载器中执行groovy脚本?

时间:2017-05-30 17:35:34

标签: java groovy classloader urlclassloader groovyclassloader

我正在尝试在隔离的类加载器中运行groovy脚本,以便它们不会在调用类的依赖项的上下文中执行。

    Path log4j = Paths.get("..../lib/log4j-1.2.17.jar");
    Path groovy = Paths.get("..../lib/groovy-all-2.1.3.jar");
    RootLoader rootLoader = new RootLoader(new URL[] { log4j.toUri().toURL(), groovy.toUri().toURL() }, null);
    GroovyScriptEngine engine = new GroovyScriptEngine(".../src/main/resources", rootLoader);
    engine.run("Standalone.groovy", "");
Standalone.groovy
import org.apache.log4j.BasicConfigurator
import org.apache.log4j.Logger

Logger logger = Logger.getLogger(getClass())
BasicConfigurator.configure()
logger.info("hello world")
pom.xml摘录
    <dependency>
        <groupId>org.codehaus.groovy</groupId>
        <artifactId>groovy-all</artifactId>
        <version>2.1.3</version>
    </dependency>

我尝试的上述任何变化都会导致

Exception in thread "main" groovy.lang.GroovyRuntimeException: Failed to create Script instance for class: class Standalone. Reason: java.lang.ClassCastException: Standalone cannot be cast to groovy.lang.GroovyObject
    at org.codehaus.groovy.runtime.InvokerHelper.createScript(InvokerHelper.java:443)
    at groovy.util.GroovyScriptEngine.createScript(GroovyScriptEngine.java:564)
    at groovy.util.GroovyScriptEngine.run(GroovyScriptEngine.java:551)
    at groovy.util.GroovyScriptEngine.run(GroovyScriptEngine.java:537)

我已将此跟踪回groovy.util.GroovyScriptEngine#loadScriptByName,其中脚本被解析为Class<T>,其中T是脚本本身的名称。

我的理论是,这是由于在调用类中运行的groovy运行时与在独立类加载器中运行的groovy运行时之间的二进制不兼容引起的,因为groovy通过反射从脚本创建合成类的方式。

关于如何实现这一目标的任何想法?

1 个答案:

答案 0 :(得分:2)

尝试不是直接创建GroovyScriptEngine,而是通过rootLoader.loadClass()创建engine.run并通过反思调用void BitmapToJpg(HBITMAP hbmpImage, int width, int height) { time_t now = time(0); char* dt = ctime(&now); Bitmap *p_bmp = Bitmap::FromHBITMAP(hbmpImage, NULL); //Bitmap *p_bmp = new Bitmap(width, height, PixelFormat32bppARGB); CLSID pngClsid; int result = GetEncoderClsid(L"image/jpeg", &pngClsid); if (result != -1) std::cout << "Encoder succeeded" << std::endl; else std::cout << "Encoder failed" << std::endl; p_bmp->Save(L"screen_.jpg", &pngClsid, NULL); delete p_bmp; }