summaryrefslogtreecommitdiffstats
path: root/src/de/fhswf/in/inf/upnfx/util/BinaryTemplate.java
blob: 6f77dc410ef27ec7d7ec53e716f2fb84613edc08 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
/**
 * 
 */
package de.fhswf.in.inf.upnfx.util;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * Uses Reflection API to get the method for calculation.
 *
 * @author $Author: $
 * @version $Revision: $, $Date: $ UTC
 */
public class BinaryTemplate extends BinaryOperator
{

   private Method operator;

   /**
    * Gets the operator function from the Math class.
    *
    * @param mathFunction
    *           The name of the operation.
    */
   public BinaryTemplate(String mathFunction)
   {
      if (mathFunction == null)
      {
         throw new IllegalArgumentException("Operation can't be null.");
      }

      if (mathFunction.isEmpty())
      {
         throw new IllegalArgumentException("Operations can't be empty.");
      }

      try
      {
         operator = Math.class.getMethod(mathFunction, Double.TYPE,
               Double.TYPE);
      }
      catch (NoSuchMethodException e)
      {
         throw new IllegalArgumentException("Not a valid Operator.", e);
      }
      catch (SecurityException e)
      {
         throw new IllegalArgumentException("Security violation.", e);
      }

   }

   /*
    * (non-Javadoc)
    * 
    * @see de.fhswf.in.inf.java1.aufgabe12.UnaryOperator#eval(double)
    */
   @Override
   final double eval(double d1, double d2)
   {
      Object tmp = null;
      try
      {
         tmp = operator.invoke(null, d1, d2);
      }
      catch (IllegalAccessException e)
      {
         throw new IllegalStateException("Can't access method.", e);
      }
      catch (IllegalArgumentException e)
      {
         throw new IllegalStateException(
               "Argument for Math function is not double.", e);
      }
      catch (InvocationTargetException e)
      {
         if (e.getCause() instanceof IllegalArgumentException)
         {
            throw new IllegalArgumentException("Illegal Argument.", e);
         }
         throw new IllegalStateException("Unexpected exception.", e);
      }
      return (double) tmp;
   }

}