Makistos
10/28/2013 - 7:55 AM

This snippet shows how to use reflection in Java to call both functions with parameters and without them and also how to set and read attrib

This snippet shows how to use reflection in Java to call both functions with parameters and without them and also how to set and read attributes. #reflection #java

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

public class ReflectionExample {
  ArrayList<Object> registeredModels;

  ReflectionExample() {
    registeredModels = new ArrayList<Object>();
  }

  public void addModel(Object model) {
    registeredModels.add(model);
  }

  public void callAllFooWithParam(int param) {
    for (Object model: registeredModels) {
      Class c = model.getClass();
      Class parTypes[] = new Class[1];
      parTypes[0] = Integer.TYPE;
      try {
        Method m = c.getMethod("foo", parTypes);
        Object argList[] = new Object[1];
        argList[0] = new Integer(param);
        m.invoke(model, argList);
      } catch (Throwable e) {
        // Just skip, this model didn't have a function called foo().
      }
    }
  }

  public void callAllFooParamless() {
    for (Object model: registeredModels) {
      Class c = model.getClass();
      Class parTypes[] = null;
      try {
        Method m = c.getMethod("foo", parTypes);
        Object argList[] = null;
        m.invoke(model, argList);
        } catch (Throwable e) {
          // Do nothing
        }
     }
  }

  public void set(String field, Object value) {
    for (Object model: registeredModels) {
      Class c = model.getClass();
      try {
        Field f = c.getDeclaredField(field);
        f.set(this, value);
      } catch (Exception e) {
        //System.err.println("Field does not exist: " + name + "(" + e.getMessage() + ")");
      }
    }
  }

  public ArrayList<Object> get(String field) {
    ArrayList<Object>retval = new ArrayList<Object>();
    for (Object model: registeredModels) {
      Class c = model.getClass();
      try {
        Field f = c.getDeclaredField(field);
        retval.add((Object)f.get(this));
      } catch (Exception e) {
        //System.err.println("Field does not exist: " + name + " (" + e.getMessage() + ")");
      }
    }
    return retval;
  }
}