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

时间:2015-05-19 18:19:44

标签: java reflection processing

我想在Processing中创建一个简单的方法队列,并尝试使用Java的本机反射。为什么getDeclaredMethod()在此示例中不起作用?有没有办法让它发挥作用?无论我尝试过它的变化,它总是返回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");
  }
}

1 个答案:

答案 0 :(得分:3)

我认为它不会返回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();
  }