2012-11-15 39 views
3

我正在挖掘Web應用程序以努力修復一些問題。該應用程序使用Tomcat,Jersey和Guice。其中一個問題發生在用於授權目的的MethodInterceptor中。這裏的方法,修剪到相關部分:獲取用於MethodInvocation而不是聲明類的實際類

public Object invoke(MethodInvocation invoc) throws Throwable { 
    // ... 

    //Check that the annotation actually exists 
    if(! invoc.getMethod().getDeclaringClass().isAnnotationPresent(Tool.class)) 
    { 
     throw new BaseException("..."); 
    } 

    // ... 
} 

現在的問題是,一些「面向網絡的」方法是從父類中繼承而沒有在孩子被覆蓋。如果我正確理解getDeclaringClass(),在這種情況下它將返回父類類,但我們真正想要的是子類。一些測試似乎證實了這一點 - 如果我重寫子類中的方法一切都很好,但如果我沒有在重寫中引發異常。

因此,給定一個MethodInvocation對象,是否有辦法將其追溯到實例化的「實際」類,而不是聲明該方法的類?還是需要其他一些方法?最壞的情況下,我可以根據需要對每種方法進行註釋,而不是對類進行註釋。

對不起,如果這是一個容易回答的長期問題 - 我的Java很生疏。

回答

4

很簡單,需要對MethodInvocation來代替getMethod().getDeclaringClass()使用getThis().getClass()

if(! invoc.getThis().getClass().isAnnotationPresent(Tool.class)) 
    { 
     throw new BaseException("..."); 
    } 

雖然在我的情況下,吉斯複雜的事情有點通過將在自動生成的子類(例如,類名在結束「$$ EnhancerByGuice ......」這是固定移動一起來的樹getSuperclass()

if(! invoc.getThis().getClass().getSuperclass().isAnnotationPresent(Tool.class)) 
    { 
     throw new BaseException("..."); 
    } 
+0

我找不到MethodInvocation.getThis()方法。它也不在文檔中:http://help.eclipse.org/juno/index.jsp?topic=%2Forg.eclipse.jdt.doc.isv%2Freference%2Fapi%2Forg%2Feclipse%2Fjdt%2Fcore%2Fdom%2FMethodInvocation .html –

+0

這是與本問題中提及的不同的軟件包/ API。我所指的類來自Guice引入的AOP類。請參閱http://aopalliance.sourceforge.net/doc/org/aopalliance/intercept/MethodInvocation.html和https://github.com/google/guice/wiki/AOP –

+0

對不起,您對了 –

0

看起來,答案是不,我創建了簡單的測試,以檢查它:

class Run implements Runnable { 
     @Override 
     public void run() { 
     } 
    } 
    class Run2 extends Run{} 
    Method method = Run2.class.getMethods()[0]; 
    System.out.println(method); 

正如我們在調試窗口看到方法不具有類RUN2的任何信息:我想這將是更好地堅持與它的註解實際方法而不是

Method in debug window

在調用這些方法的實際類實例上。

+0

這確實有道理。幸運的是,'MethodInvocation'類可以通過'getThis()'獲得調用方法的實例。通過這種方式,我可以在實例上調用getClass(),並避免碰到使用方法元數據時看到的障礙。 –

相關問題