2015-05-19 29 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(); 
    } 
相關問題