1.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000
1.2 +++ b/samples/composition/src-api2.0-runtime/api/Arithmetica.java Sat Jun 14 09:58:13 2008 +0200
1.3 @@ -0,0 +1,64 @@
1.4 +package api;
1.5 +
1.6 +import org.apidesign.runtime.check.RuntimeCheck;
1.7 +
1.8 +/** Class to simplify arithmetical operations, improved version to compute
1.9 + * the sum for ranges, but only if the virtual machine is configured to
1.10 + * run in incompatible mode.
1.11 + *
1.12 + * @author Jaroslav Tulach <jtulach@netbeans.org>
1.13 + * @version 2.0
1.14 + */
1.15 +public class Arithmetica {
1.16 + public int sumTwo(int one, int second) {
1.17 + return one + second;
1.18 + }
1.19 +
1.20 + public int sumAll(int... numbers) {
1.21 + int sum = numbers[0];
1.22 + for (int i = 1; i < numbers.length; i++) {
1.23 + sum = sumTwo(sum, numbers[i]);
1.24 + }
1.25 + return sum;
1.26 + }
1.27 +
1.28 + public int sumRange(int from, int to) {
1.29 + if (calledByV2AwareLoader()) {
1.30 + return sumRange2(from, to);
1.31 + } else {
1.32 + return sumRange1(from, to);
1.33 + }
1.34 + }
1.35 +
1.36 + private int sumRange1(int from, int to) {
1.37 + int len = to - from;
1.38 + int[] array = new int[len + 1];
1.39 + for (int i = 0; i <= len; i++) {
1.40 + array[i] = from + i;
1.41 + }
1.42 + return sumAll(array);
1.43 + }
1.44 +
1.45 + private int sumRange2(int from, int to) {
1.46 + return (from + to) * (to - from + 1) / 2;
1.47 + }
1.48 +
1.49 + private static boolean calledByV2AwareLoader() {
1.50 + // BEGIN: design.composition.arith2.6.runtime
1.51 + StackTraceElement[] arr = Thread.currentThread().getStackTrace();
1.52 + ClassLoader myLoader = Arithmetica.class.getClassLoader();
1.53 + for (int i = 0; i < arr.length; i++) {
1.54 + ClassLoader caller = arr[i].getClass().getClassLoader();
1.55 + if (myLoader == caller) {
1.56 + continue;
1.57 + }
1.58 + if (RuntimeCheck.requiresAtLeast("2.6", "api.Arithmetica", caller)) {
1.59 + return true;
1.60 + }
1.61 + return false;
1.62 + }
1.63 + return true;
1.64 + // END: design.composition.arith2.6.runtime
1.65 + }
1.66 +
1.67 +}