samples/composition/src-api2.0-runtime/api/Arithmetica.java
author Jaroslav Tulach <jtulach@netbeans.org>
Sat, 14 Jun 2008 09:58:13 +0200
changeset 155 c00f947c0936
child 184 6b2cd8df14c0
permissions -rw-r--r--
Adding example, however only a sketch, of possible runtime check between alternative versions
     1 package api;
     2 
     3 import org.apidesign.runtime.check.RuntimeCheck;
     4 
     5 /** Class to simplify arithmetical operations, improved version to compute
     6  * the sum for ranges, but only if the virtual machine is configured to
     7  * run in incompatible mode.
     8  *
     9  * @author Jaroslav Tulach <jtulach@netbeans.org>
    10  * @version 2.0
    11  */
    12 public class Arithmetica {
    13     public int sumTwo(int one, int second) {
    14         return one + second;
    15     }
    16     
    17     public int sumAll(int... numbers) {
    18         int sum = numbers[0];
    19         for (int i = 1; i < numbers.length; i++) {
    20             sum = sumTwo(sum, numbers[i]);
    21         }
    22         return sum;
    23     }
    24     
    25     public int sumRange(int from, int to) {
    26         if (calledByV2AwareLoader()) {
    27             return sumRange2(from, to);
    28         } else {
    29             return sumRange1(from, to);
    30         }
    31     }
    32 
    33     private int sumRange1(int from, int to) {
    34         int len = to - from;
    35         int[] array = new int[len + 1];
    36         for (int i = 0; i <= len; i++) {
    37             array[i] = from + i;
    38         }
    39         return sumAll(array);
    40     }
    41     
    42     private int sumRange2(int from, int to) {
    43         return (from + to) * (to - from + 1) / 2;
    44     }
    45 
    46     private static boolean calledByV2AwareLoader() {
    47         // BEGIN: design.composition.arith2.6.runtime
    48         StackTraceElement[] arr = Thread.currentThread().getStackTrace();
    49         ClassLoader myLoader = Arithmetica.class.getClassLoader();
    50         for (int i = 0; i < arr.length; i++) {
    51             ClassLoader caller = arr[i].getClass().getClassLoader();
    52             if (myLoader == caller) {
    53                 continue;
    54             }
    55             if (RuntimeCheck.requiresAtLeast("2.6", "api.Arithmetica", caller)) {
    56                 return true;
    57             }
    58             return false;
    59         }
    60         return true;
    61         // END: design.composition.arith2.6.runtime
    62     }
    63     
    64 }