In my previous post, I showed how the parameters to a JavaScript function can be supplied with Java. The next step is to supply other variables. The simplest way to set some variable values is to use ScriptEngine.put(name, value): ScriptEngine engine = …; engine.put(“taxRate”, 0.0825); // 8.25% // evaluate script // invoke function Now the [...]
Picking up where I left off in the previous post, I am going to cover some ways to get data into a script. Here’s how to simply supply parameter values when calling a function defined in a script. First the ScriptRunner needs to be updated: pubic class ScriptRunner { … public void load(String scriptName) throws [...]
I gravitate towards writing testing infrastructure. I find it very rewarding to see my frameworks, abstractions and convenience APIs being used by my coworkers. As the testing gets further and further away from unit tests, having scripting capabilities tends to become increasingly important. In the past, I’ve used BeanShell, jython and various DSLs to support [...]
Some meaty documentation for dynamic proxies can be found in the javadoc for java.lang.reflect.Proxy. One detail specifically called out is how calls to a proxy instance’s equals(), hashCode() and toString() are dispatched to the invocation handler. The design subtlety turns out be important and well thought-out. To understand why, it is first important to grasp [...]
Java 1.3 introduced java.lang.reflect.Proxy, which allows code to dynamically implement interfaces. This is done by asking Java to create a proxy around an InvocationHandler that you define. Whenever a method on the proxy is invoked, the proxy delegates the invocation to the invocation handler. For example, the call someMethod(“arg1″, “arg2″) is invoked on proxy3 would [...]
Convenient ways to instantiate genericized types, pre-populated Lists, Sets and Java arrays using varargs and generic methods. These are very useful when writing code that needs to create several collections of pre-defined content, unit tests being classic examples.
In my previous post, I (intentionally) omitted various important technical and theoretical details. Here, I look at the concept of Dynamic Dispatching, and how it fits with the simple prettyToString() example. Dynamic dispatching is what makes polymorphic behavior happen. When you call toString() on an object, the right implementation is called because Java dispatches to [...]
Scenario: Sometimes, we need to add a behavior to several classes, where we cannot modify the classes. For example, imagine wanting to add prettyToString() to Strings, Numbers, Booleans, Collections and Maps. A first stab at the code may look like this: public static String prettyToString(Object input) { if (input instanceof String) { return prettyToString((String) input); [...]