Couldn't really figure out/find what a difference between thouse two
import groovy.lang.Binding;
import groovy.lang.GroovyShell;
class Scratch {
public static void main(String[] args) {
Binding binding = new Binding();
Integer p = 1,
v = 1;
binding.setProperty("p", p);
binding.setVariable("v", v);
GroovyShell shell = new GroovyShell(binding);
shell.evaluate("p++;v++;");
System.out.println(String.format("BINDING Property = %s, Variable = %s", binding.getProperty("p"), binding.getVariable("v")));
System.out.println(String.format("JAVA Property = %s, Variable = %s", p, v));
}
}
Run Code Online (Sandbox Code Playgroud)
Output is:
BINDING Property = 2, Variable = 2
JAVA Property = 1, Variable = 1
Run Code Online (Sandbox Code Playgroud)
Is there is some purpose for using one or another.
类groovy.lang.Binding重载setProperty和getProperty方法,以便您可以使用字段访问器或下标运算符访问变量。如果你看一下这两个方法的源代码,你会发现类似这样的内容:
/**
* Overloaded to make variables appear as bean properties or via the subscript operator
*/
public Object getProperty(String property) {
/** @todo we should check if we have the property with the metaClass instead of try/catch */
try {
return super.getProperty(property);
}
catch (MissingPropertyException e) {
return getVariable(property);
}
}
/**
* Overloaded to make variables appear as bean properties or via the subscript operator
*/
public void setProperty(String property, Object newValue) {
/** @todo we should check if we have the property with the metaClass instead of try/catch */
try {
super.setProperty(property, newValue);
}
catch (MissingPropertyException e) {
setVariable(property, newValue);
}
}
Run Code Online (Sandbox Code Playgroud)
这意味着在 Groovy 中你可以表达
/**
* Overloaded to make variables appear as bean properties or via the subscript operator
*/
public Object getProperty(String property) {
/** @todo we should check if we have the property with the metaClass instead of try/catch */
try {
return super.getProperty(property);
}
catch (MissingPropertyException e) {
return getVariable(property);
}
}
/**
* Overloaded to make variables appear as bean properties or via the subscript operator
*/
public void setProperty(String property, Object newValue) {
/** @todo we should check if we have the property with the metaClass instead of try/catch */
try {
super.setProperty(property, newValue);
}
catch (MissingPropertyException e) {
setVariable(property, newValue);
}
}
Run Code Online (Sandbox Code Playgroud)
作为
binding.setVariable("v", v);
Run Code Online (Sandbox Code Playgroud)
当然,如果您正在访问的属性setProperty或getProperty类中存在该属性,那么您将无法使用该名称设置变量,在这种情况下,您需要调用binding.setVariable()直接调用。
另一方面,方法getVariable和setVariable直接读取或将值放入内部映射。它的源代码如下:
binding.v = v
// or
binding['v'] = v
Run Code Online (Sandbox Code Playgroud)