Класс 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);
}