我正在尝试使用ConditionalInterrupt使Groovy抛出InterruptedException。我正在尝试用Java构建它。这就是我到目前为止所做的事情
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);
}
仅仅是一个FYI,下面的代码块代表我为完成这项工作所做的最后几次尝试......(一旦我们得到正确的答案,将删除它)
binding.setVariable("p", p);
final GroovyShell shell1 = new GroovyShell(binding);
final Closure closure2 = (Closure) shell1
.evaluate("{ it -> p.isEmpty() }");
//final Closure closure2 = (Closure) shell1
// .evaluate("{ p -> p.isEmpty() }");
final BlockStatement code = (BlockStatement) new AstBuilder()
.buildFromString("def p = { System.out.println(1) }").get(0);
final ClosureExpression cex = (ClosureExpression) ((ReturnStatement) code
.getStatements().get(0)).getExpression();
// final Expression expression = new BooleanExpression(
// new MethodCallExpression(new VariableExpression("p"),
// "isEmpty", new TupleExpression()));
// final Expression expression = new MethodPointerExpression(
// new VariableExpression("p"), new ConstantExpression("isEmpty"));
// // final Statement code = new ExpressionStatement(expression);
final ClosureExpression closure = new ClosureExpression(
new Parameter[0], code);
annotationParameters.put("value", cex);
答案 0 :(得分:0)
你可以做到,但你应该自己建立封闭!
例如,我的代码,闭包表达式检查静态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));
Groovy非常强大!