Java reflection in Processing: "Unhandled exception type NoSuchMethodException"

I'm trying to use Java reflection in order to achieve something similar to what ControlP5 does (where you can register a variable or function of an object, and dynamically call / manipulate it).

I can't even get the simplest test to work though, all I get is the "Unhandled exception type NoSuchMethodException". From researching online I understand that part of the puzzle has to do with all classes defined within the Processing environment are inner classes, but that doesn't really help me. (I've forgotten most of my Java during years of Flash and Javascript work... ;) ) I'm not building any big applications here, so I'm not overly concerned with best practices and convoluted design patterns. Is there a quick and dirty way to accomplish what I want?

import java.lang.reflect.Method;

void setup() {
    ReflectionTester t = new ReflectionTester(this);
}

void testFunction() {
    println("i'm called!");
}

public class ReflectionTester {
    public ReflectionTester (Object obj) {
        Method m = obj.getClass().getMethod("testFunction");
        m.invoke(obj);
    }
}

Answers

  • edited January 2016 Answer ✓

    Whenever we got "Unhandled exception...", it means it's a "checked" Exception & demands try/catch ():

    // forum.Processing.org/two/discussion/9919/
    // java-reflection-in-processing-unhandled-exception-type-nosuchmethodexception
    
    void setup() {
      new ReflectionTester(this, "testFunction");
      exit();
    }
    
    void testFunction() {
      println("I'm called!");
    }
    
    class ReflectionTester {
      ReflectionTester(Object instance, String method) {
        try {
          instance.getClass().getMethod(method).invoke(instance);
        }    
        catch (ReflectiveOperationException e) {
          throw new RuntimeException(e);
        }
      }
    }
    
  • Doh! It was that simple? I didn't realize there were cases you had to use try/catch. Thanks a lot! :)

  • edited January 2016

    I'm not overly concerned with best practices...
    Is there a quick and dirty way to accomplish what I want?

    // forum.Processing.org/two/discussion/9919/
    // java-reflection-in-processing-unhandled-exception-type-nosuchmethodexception
    
    void setup() {
      new ReflectionTester(this, "testFunction");
      exit();
    }
    
    void testFunction() {
      println("I'm called!");
    }
    
    class ReflectionTester {
      ReflectionTester(PApplet p, String method) {
        p.method(method);
      }
    }
    
Sign In or Register to comment.