Maison  >  Questions et réponses  >  le corps du texte

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 Il y a quelques jours358

répondre à tous(1)je répondrai

  • 伊谢尔伦

    伊谢尔伦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;

    répondre
    0
  • Annulerrépondre