/*
 * JBoss, the OpenSource EJB server
 *
 * Distributable under LGPL license.
 * See terms of license at gnu.org.
 */
package org.jboss.ejb3.injection;

import java.lang.reflect.Field;
import javax.management.MBeanServer;
import javax.management.MBeanServerFactory;
import javax.management.ObjectName;
import org.jboss.ejb3.BeanContext;
import org.jboss.mx.util.MBeanProxyExt;

/**
 * @author <a href="mailto:kabir.khan@jboss.org">Kabir Khan</a>
 * @version $Revision: 1.1.4.4 $
 */
public class DependsFieldInjector implements Injector
{
   Field field;
   ObjectName on;

   public DependsFieldInjector(Field field, ObjectName on)
   {
      this.field = field;
      this.on = on;
   }

   public void inject(BeanContext ctx)
   {
      Class clazz = field.getType();
      Object value = null;

      if (clazz == ObjectName.class)
      {
         value = on;
      }
      else
      {
         MBeanServer server = (MBeanServer) MBeanServerFactory.findMBeanServer(null).get(0);
         value = MBeanProxyExt.create(clazz, on, server);
      }

      try
      {
         field.set(ctx.getInstance(), value);
      }
      catch (IllegalAccessException e)
      {
         throw new RuntimeException(e);
      }
   }
}
