首頁  >  問答  >  主體

java - struts2 拦截器内 invoke 方法返回空

我的 struts2 拦截器内有以下代码

@Override
public String intercept(ActionInvocation ai) throws Exception {
    Object object = ai.getAction();
    Class<? extends Object> clazz = ai.getAction().getClass();
    Field[] fields = clazz.getDeclaredFields();

    try {
        for(Field field : fields) {
            PropertyDescriptor pd = null;
            try {
                pd = new PropertyDescriptor(field.getName(), clazz);  
            } catch (Exception e) {
                continue;
            }
                
            Method getMethod = pd.getReadMethod();     
            Method setMethod = pd.getWriteMethod();    
                
            Object o = getMethod.invoke(object); 
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}    

但是这句 Object o = getMethod.invoke(object); 里的 o 一直都是 null,这是为什么?

大家讲道理大家讲道理2721 天前360

全部回覆(1)我來回復

  • 伊谢尔伦

    伊谢尔伦2017-04-17 15:08:18

    你要取得的目標欄位在程式邏輯上是 action執行完之後才得到的,還是只要有action物件才能取得?

    如果是前置,你需要在攔截器裡完成呼叫鏈的執行:

    String result = ai.invoke();
    Object object = ai.getAction();
    Class<? extends Object> clazz = ai.getAction().getClass();
    Field[] fields = clazz.getDeclaredFields();
    
    try {
        for(Field field : fields) {
            PropertyDescriptor pd = null;
            try {
                pd = new PropertyDescriptor(field.getName(), clazz);  
            } catch (Exception e) {
                continue;
            }
                
            Method getMethod = pd.getReadMethod();     
            Method setMethod = pd.getWriteMethod();    
                
            Object o = getMethod.invoke(object); 
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    return result;

    回覆
    0
  • 取消回覆