2015-05-19 58 views
1

我想在Processing中创建一个简单的方法队列,我试图用Java的本地反射来实现它。为什么getDeclaredMethod()不适用于此示例?有没有办法让它工作?不管它的变化,我都试过了,它总是返回NoSuchMethodException ...为什么我不能在Processing中使用Java的getDeclaredMethod()?

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"); 
    } 
} 

回答

3

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

Unhandled exception type NoSuchMethodException

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

换句话说,你没有得到NoSuchMethodException。你得到一个编译器错误,因为你没有将getDeclaredMethod()包装在try-catch块中。要解决这个问题,只需在您的电话中添加一个try-catch块,以便getDeclaredMethod()

try{ 
    Method m = myClass.getDeclaredMethod("doSomething"); 
    println("doSomething: " + m); 
    } 
    catch(NoSuchMethodException e){ 
    e.printStackTrace(); 
    } 
相关问题