Pàgines

Nov 4, 2011

Send a method / function as a parameter in Processing

To send a method or a function as a parameter you can use the folloing code.
This code is also usable in Android-Processing and Java.

import java.lang.reflect.Method;
import java.lang.reflect.InvocationTargetException;

///////////////////////////////// Metode class ////////////////////////////// 
class Metode{
  Object obj;             // objecte que conté el mètode que HA de ser PUBLIC
  Method method;
  
  Metode(Object lobj, String lnomMetode, Class... parametres) {
    obj = lobj;
    
    try {
      method = lobj.getClass().getMethod(lnomMetode, parametres);     //parametres = new Class[] {  }  ||  new Class[] { int.class, float.class }
    } catch (NoSuchMethodException nsme) {
      System.err.println("There is no " + lnomMetode + "() method " + "in the class " + obj.getClass().getName());
    } catch (Exception e) {
      e.printStackTrace();
    } 
  }////////
 

 
  Object run(Object... parametres) {
    try {
      return(method.invoke(obj, parametres));                  //parametres = new Object[] {  }  ||  new object[] { 1, 5.1 }
    } catch (IllegalArgumentException e) {
      e.printStackTrace();
    } catch (IllegalAccessException e) {
      e.printStackTrace();
    } catch (InvocationTargetException e) {
      e.getTargetException().printStackTrace();
    } catch (Exception e) {
      e.printStackTrace();
    }
    return(null);
  }////////  
  
}//end class Metode


///////////////////////////// Example //////////////////////////

A aObj = new A();
C cObj = new C();

void setup(){
  Metode a = new Metode(  aObj, "metA", int.class, float.class  );
  a.run(3, 5.1);  // prints '3 5.1'
  
  rebMetode(  new Metode(  this, "metB")  );  // prints 'hola'
  
  Metode c = new Metode(  cObj, "metC", int.class  );
  int res = (Integer)c.run(2);  // prints 'Has dit: 2 i jo et dic: 12' 
  println(res);  // prints '12'
}


void rebMetode(Metode metode){  metode.run();  }


public void metB(){  println("hola");  }

class A{  A(){}  public void metA(int i, float f){  println(i+" "+f);                                                   }  }
class C{  C(){}  public int  metC(int i)         {  println("Has dit: " + i + " i jo et dic: "+(i+10));  return(i+10);  }  }

////////////////////////////// Example End ///////////////////////////////////