为什么我不能在 Processing 中使用 Java 的 getDeclaredMethod()?

Why can't I use Java's getDeclaredMethod() in Processing?

我想在 Processing 中创建一个简单的方法队列,我正在尝试使用 Java 的本机反射来实现。为什么 getDeclaredMethod() 在此示例中不起作用?有没有办法让它工作?无论我尝试过什么变化,它总是 returns NoSuchMethodException...

import java.lang.reflect.Method;

void draw() {
  Testclass t = new Testclass();
  Class myClass = t.getClass();
  println("Class: " + myClass);

  // This doesn't work...
  Method m = myClass.getDeclaredMethod("doSomething");

  // This works just fine...
  println(myClass.getDeclaredMethods());

  exit();
}



// Some fake class...
class Testclass {
  Testclass() {
  }

  public void doSomething() {
    println("hi");
  }
}

我认为它不会返回 NoSuchMethodException。您看到的错误是:

Unhandled exception type NoSuchMethodException

你看到这个是因为 getDeclaredMethod() 可以 抛出一个 NoSuchMethodException,所以你必须把它放在 try-catch 块中。

换句话说,您没有得到 NoSuchMethodException。您收到编译器错误,因为您没有将 getDeclaredMethod() 包装在 try-catch 块中。要修复它,只需在对 getDeclaredMethod().

的调用周围添加一个 try-catch 块
  try{
    Method m = myClass.getDeclaredMethod("doSomething");
    println("doSomething: " + m);
  }
  catch(NoSuchMethodException e){
    e.printStackTrace();
  }