sixlegs.com / blog / java / bfn9000.html

Root Beer Logo Root Beer

Chris Nokleberg's Fizzy Weblog

October 2005
Su M Tu W Th F Sa
            1
2 3 4 7 8
9 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31
Previous  |  Next  |  More...
#  BFN9000

Today I stumbled across Wilfred Springer's blog. He recently had an interesting idea of using annotation and/or bytecode generation to simplify the use of BigDecimals. Just for fun I decided to implement something simple using CGLIB.

The first step is to write an abstract class that has the method signatures of every function you need. The @Big method annotation is then used to actually describe the equations:

import com.sixlegs.bfn9000.Big;
import java.math.BigDecimal;

abstract public class Example
{
    @Big("(* (^ a 2) 3.1415926535897932384626433832795)")
    abstract public BigDecimal area(BigDecimal r);
}

At runtime, the Compiler class is used to create a concrete instance, after which you can call the methods directly:

// create a concrete instance of the abstract class
Example ex = new com.sixlegs.bfn9000.Compiler().compile(Example.class);

// calculate the area of a circle with radius 4
BigDecimal area = ex.area(new BigDecimal("4"))

This is similar to Voruta, which uses the same technique to provide a clean Java interface to embedded SQL statements. Like Voruta, the current implementation uses CGLIB to proxy the abstract class. The expressions are parsed ahead of time but interpreted for each method call. I first considered using ASM to generate the bytecode directly, and I still might do that at some point, but I believe Wilfred when he said his bytecode-based version wasn't as fast as he hoped. Also, I cheated a bit by using prefix notation for the equations (easier to parse), and there is no link between the variable names and the method argument names ("a"-"z" in the equations always map to arguments 0-25).

If anyone wants to play around with this, I've put up a source distribution that includes everything you need except CGLIB. Just drop cglib-nodep-2.1_2.jar into the lib directory and run "ant test". License is GPL+Library exception (same as GNU Classpath)

[Powered By FreeMarker]  [Valid Atom 1.0]  [Weblog Commenting by HaloScan.com]