From c1a240e873cb0e434ea98506d2f33b4a571e354a Mon Sep 17 00:00:00 2001 From: Stefan Suhren Date: Tue, 6 Jan 2015 11:43:01 +0100 Subject: Assignment No.12 first complete implementation. --- .../in/inf/java1/aufgabe12/UnaryTemplate.java | 86 ++++++++++++++++++++++ 1 file changed, 86 insertions(+) create mode 100644 src/de/fhswf/in/inf/java1/aufgabe12/UnaryTemplate.java (limited to 'src/de/fhswf/in/inf/java1/aufgabe12/UnaryTemplate.java') diff --git a/src/de/fhswf/in/inf/java1/aufgabe12/UnaryTemplate.java b/src/de/fhswf/in/inf/java1/aufgabe12/UnaryTemplate.java new file mode 100644 index 0000000..d345af1 --- /dev/null +++ b/src/de/fhswf/in/inf/java1/aufgabe12/UnaryTemplate.java @@ -0,0 +1,86 @@ +/** + * + */ +package de.fhswf.in.inf.java1.aufgabe12; + +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 UnaryTemplate extends UnaryOperator +{ + + private Method operator; + + /** + * Gets the operator function from the Math class. + * + * @param mathFunction + * The name of the operation. + */ + public UnaryTemplate(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); + } + 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 d) + { + Object tmp = null; + try + { + tmp = operator.invoke(null, d); + } + 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; + } + +} -- cgit v1.2.3-70-g09d2