如何从Java设置Groovy ConditionalInterrupt?
我正在尝试使用ConditionalInterrupt使Groovy抛出InterruptedException。我正在尝试从Java构建它。这就是我到目前为止所做的如何从Java设置Groovy ConditionalInterrupt?,java,groovy,Java,Groovy,我正在尝试使用ConditionalInterrupt使Groovy抛出InterruptedException。我正在尝试从Java构建它。这就是我到目前为止所做的 final Binding binding = new Binding(); final CompilerConfiguration config = new CompilerConfiguration(); final Map<String, Object> annotationParameters = new Ha
final Binding binding = new Binding();
final CompilerConfiguration config = new CompilerConfiguration();
final Map<String, Object> annotationParameters = new HashMap<String, Object>();
// this is my control variable, the code should only work if p is ""
final String p = "X";
// at this point I tried various things primarily to get the following closure
// { p.isEmpty() }
// intetionally removed because it looked really messy
annotationParameters.put("value", aStatementContainingClosure);
config.addCompilationCustomizers(new ASTTransformationCustomizer(
annotationParameters, ConditionalInterrupt.class));
final GroovyShell shell = new GroovyShell(binding, config);
try {
shell.evaluate("def a = 1;");
fail("Should not reach here");
} catch (final Exception e) {
e.printStackTrace();
assertTrue(e instanceof InterruptedException);
}
您可以这样做,但您应该自己构建闭包 例如,我的代码、闭包表达式检查静态volatile字段
Map<String, Object> map = new HashMap<>();
try {
map.put("value", new ClosureExpression(Parameter.EMPTY_ARRAY,
GeneralUtils.returnS(GeneralUtils.eqX(
GeneralUtils.fieldX(FieldNode.newStatic(ScriptService.class, "run")),
GeneralUtils.constX(false))
)));
} catch (SecurityException | NoSuchFieldException e) {
throw new RuntimeException(e);
}
configuration.addCompilationCustomizers(
new ASTTransformationCustomizer(map, ConditionalInterrupt.class));
Map Map=newhashmap();
试一试{
map.put(“value”),新的ClosureExpression(Parameter.EMPTY_数组,
GeneralUtils.returnS(GeneralUtils.eqX(
GeneralUtils.fieldX(FieldNode.newStatic(ScriptService.class,“run”)),
通用常量(错误))
)));
}catch(SecurityException | NoSuchFieldException e){
抛出新的运行时异常(e);
}
configuration.addCompilerCustomizers(
新的ASTTransformationCustomizer(map,ConditionalInterrupt.class));
Groovy真的很强大 在黑暗中完成刺杀(没有尝试过),但您可以这样做:
objectastatementcainingclosure=newgroovyshell().evaluate(“{p->p.isEmpty()”)代码>是的,试过了。工作不好。不是应该是{!p.isEmpty()}
?我尝试了这两种方法,基本上我的结果是要么应用AST转换失败,要么我的尝试总是会碰到fail()块。嗯……这是我能得到的最接近的结果,但它说找不到p
:-(
Map<String, Object> map = new HashMap<>();
try {
map.put("value", new ClosureExpression(Parameter.EMPTY_ARRAY,
GeneralUtils.returnS(GeneralUtils.eqX(
GeneralUtils.fieldX(FieldNode.newStatic(ScriptService.class, "run")),
GeneralUtils.constX(false))
)));
} catch (SecurityException | NoSuchFieldException e) {
throw new RuntimeException(e);
}
configuration.addCompilationCustomizers(
new ASTTransformationCustomizer(map, ConditionalInterrupt.class));