我是靠谱客的博主 老迟到口红,最近开发中收集的这篇文章主要介绍java 嵌入groovy,在Java中嵌入Groovy(绑定),觉得挺不错的,现在分享给大家,希望可以做个参考。

概述

I try to Bind Variables to Groovy and from Groovy back zu Java:

Java code:

Binding binding = new Binding();

binding.setVariable("SRESULT", "foo");

GroovyShell gs = new GroovyShell(binding);

gs.evaluate(script);

String sResult = (String) gs.getContext().getVariable("SRESULT");

System.out.println("FROM GROOVY: " + sResult);

Groovy Code:

class Est {

static SRESULT

public static void main(String[] args) {

println 'From Java: '+SRESULT

SRESULT = 'bar'

}

}

Output:

From Java: foo

FROM GROOVY: foo

My Question: I want to change SRESULT in Groovy and have access to the Value in Java.

Can anybody help me?

解决方案

The binding only applies to scripts, not to classes. If your Groovy code were a script, i.e. just the content of the main method without the surrounding class body

println 'From Java: '+SRESULT

SRESULT = 'bar'

then it would produce the result you expect. In particular you must not declare the SRESULT variable in the script, i.e.

def SRESULT = 'bar'

would not work. This is because the declarations (with def or with an explicit type) create local variables within the script, they do not assign to the binding.

最后

以上就是老迟到口红为你收集整理的java 嵌入groovy,在Java中嵌入Groovy(绑定)的全部内容,希望文章能够帮你解决java 嵌入groovy,在Java中嵌入Groovy(绑定)所遇到的程序开发问题。

如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(42)

评论列表共有 0 条评论

立即
投稿
返回
顶部