无法真正弄清楚/找到两者之间的区别
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);
}
关于java - groovy.lang.Binding属性和变量的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53594351/