Skip to content

Instantly share code, notes, and snippets.

@timpulver
Created September 24, 2012 16:41
Show Gist options
  • Save timpulver/3776917 to your computer and use it in GitHub Desktop.
Save timpulver/3776917 to your computer and use it in GitHub Desktop.
[Processing] Reflection Test [Java, Reflection API]
import java.lang.reflect.*;
class CallerWithoutParams{
/**
@param o the object which contains the method to call,
when passing 'this' from within the processing main sketch,
all functions in your main sketch will be recognized
(setup(), draw(),..., custom methods)
@param m the name of the method to call without "()"
*/
public void callMeBackPlease(Object o, String m){
{
if(o==null || m=="" || m==null){
println("There was an error with your arguments");
return;
}
try {
Class c = o.getClass();
Method method = c.getDeclaredMethod(m, null);
method.invoke(o);
}
catch (Throwable e) {
System.err.println(e);
}
}
}
}
import java.lang.reflect.*;
import java.io.File;
class CallerWithParams{
/**
@param o the object which contains the method to call,
when passing 'this' from within the processing main sketch,
all functions in your main sketch will be recognized
(setup(), draw(),..., custom methods)
@param m the name of the method to call without "()"
*/
public void callMeBackPlease(Object o, String m){
{
if(o==null || m=="" || m==null){
println("There was an error with your arguments");
return;
}
try {
Class c = o.getClass();
//Method m[] = c.getDeclaredMethods();
//for (int i = 0; i < m.length; i++)
//System.out.println(m[i].toString());
Class parTypes[] = new Class[1];
//File dumbFile = new File("");
//Class<? extends File> fileClass = dumbFile.getClass();
//parTypes[0] = fileClass;
parTypes[0] = new String("").getClass();
Method method = c.getDeclaredMethod(m, parTypes);
Object[] params = new Object[1];
//params[0] = new File("C:\\Users\\Powder\\Desktop\\test.txt");
params[0] = new String("WAZZUPPPP??");
method.invoke(o, params);
}
catch (Throwable e) {
System.err.println(e);
}
}
}
}
/**
* Author: Tim Pulver
* Date: 2011
*
* Tested with Processing 2.0a6
*
* A test for the java reflection API, which is useful if you want to call a function at runtime by it's name.
*/
void setup(){
CallerWithoutParams cwop = new CallerWithoutParams();
CallerWithParams cwp = new CallerWithParams();
cwop.callMeBackPlease(this, "callMe");
cwp.callMeBackPlease(this, "callMe");
}
void callMe(){
println("Yeah I got called......(no one answering)");
}
void callMe(String s){
println("Yeah I got called......" + s);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment