/************************************************************************** /* A simple demo class for dynamic method-invocation using reflection /* /* Copyright (c) 2004 by Bernhard Bablok (mail@bablokb.de) /* /* This program is free software; you can redistribute it and/or modify /* it under the terms of the GNU General Public License as published /* by the Free Software Foundation; either version 2 of the License or /* (at your option) any later version. /* /* This program is distributed in the hope that it will be useful, but /* WITHOUT ANY WARRANTY; without even the implied warranty of /* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the /* GNU General Public License for more details. /* /* You should have received a copy of the GNU General Public License /* along with this program; see the file COPYING. If not, write to /* the Free Software Foundation Inc., 59 Temple Place - Suite 330, /* Boston, MA 02111-1307 USA /**************************************************************************/ import java.lang.reflect.*; import java.io.*; import java.util.*; /** A simple demo class for dynamic method-invocation using reflection @version $Revision: 1.1 $ @author $Author: bablokb $ */ public class MathCalc { ////////////////////////////////////////////////////////////////////////////// /** Parse a given call. The method name is the first element in the linked list. @param line The argument line. */ private LinkedList parse(String line) { StringTokenizer tokenizer = new StringTokenizer(line," \t\n\r\f,()"); LinkedList list = new LinkedList(); while (tokenizer.hasMoreTokens()) list.add(tokenizer.nextToken()); return list; } ////////////////////////////////////////////////////////////////////////////// /** Search for the correct method in {@link java.lang.Math}. @param list The linked list with method name and arguments. */ private Method searchMethod(LinkedList list) throws NoSuchMethodException { if (list.size() < 1) throw new IllegalArgumentException("empty line!"); String name = (String) list.removeFirst(); Class[] args = new Class[list.size()]; for (int i=0;i "); String line = input.readLine(); if (line == null) break; else if (line.length() == 0) continue; else { try { long t1 = System.currentTimeMillis(); LinkedList list = mc.parse(line); long t2 = System.currentTimeMillis(); Method m = mc.searchMethod(list); long t3 = System.currentTimeMillis(); Object result = mc.execute(m,list); long t4 = System.currentTimeMillis(); System.out.println(result.toString() + "\n\tparse: " + (t2-t1) + "msec" + "\n\tsearch: " + (t3-t2) + "msec" + "\n\texecute: " + (t4-t3) + "msec\n"); } catch (Exception e2) { System.out.println("error: " + e2.toString()); } } } input.close(); } catch (Exception e) { e.printStackTrace(); } } }