Java Reference
In-Depth Information
sion ), and application scope ( ServletContext ). Remember that in Groovy all oper-
ators correspond to methods. In this case, the get and set methods correspond to the
dot operator, and the getAt and putAt methods implement the array subscript oper-
ator. Before I show an example, take a look at a portion of the actual implementation
class, groovy.servlet.ServletCategory , in the following listing, implemented
in Java.
Listing 10.2. Methods for HttpSession from groovy.servlet.ServletCategory
public class ServletCategory {
public static Object get(HttpSession session, String key) {
return session.getAttribute(key);
}
...
public static Object getAt(HttpSession session, String key) {
return session.getAttribute(key);
}
...
public static void set(HttpSession session,
String key, Object value) {
session.setAttribute(key, value);
}
...
public static void putAt(HttpSession session,
String key, Object value) {
session.setAttribute(key, value);
}
}
The first interesting thing to note is that this class is written in Java (!), even though it's be-
ing used in Groovy. When overloading operators, Groovy doesn't care which language you
use to implement the methods, only that you use the operators that delegate to the methods
in Groovy. In this case, I don't even plan to use the methods directly. Instead, I'm using the
dot operator and/or the array subscript notation to invoke them implicitly.
The other important detail here is that all the methods are delegating to either the getAt-
tribute or setAttribute method. The effect is that either the dot operator or the
subscript operator can be used to add attributes to the page, request, session, or application
scope.
Search WWH ::




Custom Search