FileDocCategorySizeDatePackage
GenericTemperatureAdapter.javaAPI DocExample2062Tue Jun 03 22:44:28 BST 1997BeansBook.Simulator

GenericTemperatureAdapter.java

// This example is from the book Developing Java Beans by Robert Englander. 
// Copyright (c) 1997 O'Reilly & Associates.
// You may study, use, modify, and distribute this example for any purpose.
// This example is provided WITHOUT WARRANTY either expressed or implied.

// Chapter 3 -- The GenericTemperatureAdapter class

package BeansBook.Simulator;

import java.lang.reflect.*;
import java.util.*;

public class GenericTemperatureAdapter 
         implements TempChangeListener // the adapter receives the events
{
   // the target object
   protected Object theTarget;

   // the class of the target object
   protected Class theTargetClass;

   // the class array for the parameters used for
   // the target method
   protected final static Class paramClasses[] = 
                 { BeansBook.Simulator.TempChangedEvent.class };

   // the mapping of source objects to callback methods
   protected Hashtable mappingTable = new Hashtable();
  
   // constructor
   public GenericTemperatureAdapter(Object target)
   {
      theTarget = target;
      theTargetClass = target.getClass();
   }

   // add an event source, along with the name of the method to call 
   // on the target when the event is received
   public void registerEventHandler(Temperature tmp, String methodName)
                 throws NoSuchMethodException
   {
      Method mthd = theTargetClass.getMethod(methodName, paramClasses);
      tmp.addTempChangeListener(this);
      mappingTable.put(tmp, mthd);    
   }

   // implement the listener method
   public void tempChanged(TempChangedEvent evt)
   {
      try
      {
         // invoke the registered method on the target
         Method mthd = (Method)mappingTable.get(evt.getSource());
         Object params[] = { evt };
         mthd.invoke(theTarget, params);
      }
      catch (IllegalAccessException e)
      {
         System.out.println(e);
      }
      catch (InvocationTargetException e)
      {
         System.out.println(e);
      }
   }
}