无法真正弄清楚/找到千个之间的区别
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));
}
}
输出为:
BINDING Property = 2, Variable = 2
JAVA Property = 1, Variable = 1
使用一个或另一个有什么目的吗。
类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);
}
}
这意味着在Groovy中可以表达
binding.setVariable("v", v);
作为
binding.v = v
// or
binding['v'] = v
当然,如果您使用setProperty
或getProperty
访问的属性存在于类中,那么您将无法使用此名称设置变量,在这种情况下,您需要直接调用binding.setVariable()
。
另一方面,方法getVariable
和setVariable
直接读取或将值放入内部映射。以下是它的源代码:
/**
* @param name the name of the variable to lookup
* @return the variable value
*/
public Object getVariable(String name) {
if (variables == null)
throw new MissingPropertyException(name, this.getClass());
Object result = variables.get(name);
if (result == null && !variables.containsKey(name)) {
throw new MissingPropertyException(name, this.getClass());
}
return result;
}
/**
* Sets the value of the given variable
*
* @param name the name of the variable to set
* @param value the new value for the given variable
*/
public void setVariable(String name, Object value) {
if (variables == null)
variables = new LinkedHashMap();
variables.put(name, value);
}