BigDecimal example

BigDecimal and 1.5-specific constructor

A BigDecimal constructor taking a single int was introduced in JDK 1.5. Under JDK 1.4, this code:

new BigDecimal(0);

produces this bytecode:

4:   new     #2; //class BigDecimal
   7:   dup
   8:   dconst_0
   9:   invokespecial   #3; //Method java/math/BigDecimal."<init>":(D)V
   12:  pop

Note the (D) constructor argument: the integer value 0 has been promoted to a double.
Under JDK 1.5, the code takes advantage of the new constructor:

4:   new     #2; //class java/math/BigDecimal
   7:   dup
   8:   iconst_0
   9:   invokespecial   #3; //Method java/math/BigDecimal."<init>":(I)V
   12:  pop

Under JDK 1.5, even if you use the -source 1.4 and -target 1.4 switches, the code still takes advantage of the new constructor.

You must use the JDK 1.4 bootclasspath in order to generate 1.4-compliant bytecode. SeeĀ http://docs.oracle.com/javase/1.5.0/docs/tooldocs/solaris/javac.html#crosscomp-example for more information:

4:   new     #2; //class java/math/BigDecimal
   7:   dup
   8:   dconst_0
   9:   invokespecial   #3; //Method java/math/BigDecimal."<init>":(D)V
   12:  pop

You can use retrotranslator to post-process the classes. Here’s the command line:

C:> java -jar c:\Retrotranslator-1.2.8-bin\retrotranslator-transformer-1.2.8.jar -srcdir .

The resulting bytecode now promotes the integer constructor argument to a BigInteger using the retrotranslator runtime support classes:

4:   new     #11; //class java/math/BigDecimal
   7:   dup
   8:   iconst_0
   9:   invokestatic    #17; //Method net/sf/retrotranslator/runtime/java/math/_BigDecimal.convertConstructorArguments:(I)Ljava/math
/BigInteger;
   12:  invokespecial   #20; //Method java/math/BigDecimal."<init>":(Ljava/math/BigInteger;)V
   15:  pop

At runtime, you’ll need to add a retrotranslator jar to the classpath. Alternatively, you can embed modified versions of the runtime classes into your classes directory or output jar by using the -embed switch. This avoids the need for the separate retrotranslator runtime component:

C:> java -jar c:\Retrotranslator-1.2.8-bin\retrotranslator-transformer-1.2.8.jar -srcdir . -embed ca.intelliware.retro.internal

The resulting bytecode now uses runtime support classes from the directory specified:

4:   new     #11; //class java/math/BigDecimal
   7:   dup
   8:   iconst_0
   9:   invokestatic    #17; //Method ca/intelliware/retro/internal/net/sf/retrotranslator/runtime/java/math/_BigDecimal.convertCons
tructorArguments:(I)Ljava/math/BigInteger;
   12:  invokespecial   #20; //Method java/math/BigDecimal."<init>":(Ljava/math/BigInteger;)V
   15:  pop

It's only fair to share...
Share on FacebookGoogle+Tweet about this on TwitterShare on LinkedIn

Leave a Reply